def index(): """Show portfolio of stocks""" # jinja values = stocks[[symbol, shares, price, value]], cash, totalvalue portfolio = db.execute( "SELECT * FROM portfolios WHERE userID = :sessionid", sessionid=session["user_id"]) cashrow = db.execute( "SELECT cash FROM users WHERE id = :sessionid", sessionid=session["user_id"]) if cashrow: cash = cashrow[0]["cash"] else: cash = 10000 stocks = [] totalvalue = cash if portfolio: for stock in portfolio: symbol = stock["symbol"] shares = stock["shares"] # lookup name and price myvalue = lookup(symbol) if not myvalue: return apology("API not working") price = myvalue["price"] value = int(shares) * float(price) stocks.append({ "symbol": symbol, "shares": shares, "price": usd(price), "value": usd(value) }) totalvalue += price * shares return render_template("index.html", stocks=stocks, cash=usd(cash), totalvalue=usd(totalvalue))
def index(): """Show portfolio of stocks""" DBcash = db.execute( "SELECT cash FROM users WHERE id = :Uid", Uid = session["user_id"] ) TOTAL_SUM = DBcash[0]['cash'] DBcash[0]['cash'] = usd(DBcash[0]['cash']) M = sumStocks(session["user_id"]) for stock in M: M[stock]['symbol'] = stock stock_info = lookup(M[stock]['symbol']) if not stock_info: apology("Database does not have contact with site for fetching prices") M[stock].update(stock_info) M[stock]['curr_total'] = M[stock]['price'] * M[stock]['amount'] M[stock]['price'] = usd( M[stock]["price"] ) TOTAL_SUM += M[stock]['total'] M[stock]['curr_total'] = usd( M[stock]['curr_total'] ) TOTAL_SUM = usd(TOTAL_SUM) N = {} for stock in M: if M[stock]['amount'] > 0: #print(f"M[stock]['symbol'] = {M[stock]['symbol']}") #print(f"M[stock] = {M[stock]}") N[M[stock]['symbol']] = M[stock] return render_template("index.html",DBcash=DBcash,DBstocks=N,TOTAL_SUM=TOTAL_SUM)
def buy(): """Buy shares of stock""" if request.method == "POST": if not request.form.get("symbol"): return apology("No stock name submitted.",400) if not request.form.get("shares"): return apology("No stock amount submitted.",400) try: a = int(request.form.get("shares")) except: return apology("invalid amount of shares.",400) if (int(request.form.get("shares")) != int(request.form.get("shares"))//1) or int(request.form.get("shares")) < 0: return apology("invalid amount of shares.",400) stock_info = lookup(request.form.get("symbol")) if not stock_info: return apology("Could not find the stock",400) DBcash = db.execute( "SELECT cash FROM users WHERE id = :Uid", Uid = session["user_id"] ) tot_price = stock_info["price"] * int(request.form.get("shares")) if int(DBcash[0]['cash']) > tot_price: result = db.execute("INSERT INTO transactions (symbol,price,amount,date,Uid) VALUES(:symbol,:price,:amount, :date,:Uid)", symbol=stock_info["symbol"], price=stock_info["price"], amount=request.form.get("shares"), date=datetime.now(), Uid=session["user_id"] ) if not result: return apology("The transaction could not be completed.") else: db.execute("UPDATE users SET cash = cash - :tot_price where id = :Uid", tot_price = tot_price, Uid = session["user_id"]) else: return apology("Insufficient funds.") return redirect("/") else: return render_template("buy.html",symbol={"symbol":"Stock symbol"})
def articles(): """Look up articles for geo.""" # Return parameter field for get request geo = request.args.get("geo") if not geo: raise RuntimeError("Geo Parameter Missing") return jsonify(lookup(geo)[0:5])
def articles(): """Look up articles for geo""" if not request.args.get("geo"): raise RuntimeError("missing geo") # grab data from helper data = lookup(request.args.get("geo")) return jsonify(data[:5])
def articles(): """Look up articles for geo""" geo = request.args.get("geo") if not geo: raise RuntimeError("no results from request.args.get(\"geo\")") results = lookup(geo) # lookup(geo) returns array of [{"link": item["link"], "title": item["title"]} for item in feed["items"]] if not results: raise RuntimeError("no results from lookup(geo)") return jsonify(results)
def history(): """Show history of transactions""" stocks = db.execute( "SELECT * FROM transactions WHERE Uid = :Uid", Uid = session["user_id"] ) for stock in stocks: stock_info = lookup(stock['symbol']) stock.update(stock_info) return render_template("history.html",DBstocks=stocks)
def quote(): """Get stock quote.""" if request.method == "POST": value = request.form.get("symbol") if not value: return apology("Please enter a valid ticker") quote = lookup(value) if not quote: return apology("Not a valid symbol") return render_template("display.html", ticker=quote["symbol"], price=usd(int(quote["price"]))) else: return render_template("quote.html")
def sell(): """Sell shares of stock""" if request.method == "POST": # form names = symbol, shares symbol = request.form.get("symbol") shares = request.form.get("shares") if not RepresentsInt(shares): return apology("You must enter a valid whole number of shares") if not symbol or not shares or int(shares) <= 0: return apology("You must enter a valid symbol and shares") quote = lookup(symbol) if not quote: return apology("Not a valid symbol, or API not working") price = quote["price"] cost = float(price) * int(shares) # look for in and then update portfolios resultPortfoliosSearch = db.execute( "SELECT shares FROM portfolios WHERE userID = :sessionid AND symbol = :symbol", sessionid=int(session["user_id"]), symbol=symbol) if int(resultPortfoliosSearch[0]["shares"]) > int(shares): # if you have it and you have extra shares, update it resultPortfoliosUpdate = db.execute("UPDATE portfolios SET shares = shares - :shares WHERE userID = :sessionid AND symbol = :symbol", sessionid=session["user_id"], symbol=symbol, shares=int(shares)) if not resultPortfoliosUpdate: return apology("You don't have enough shares of that stock") elif resultPortfoliosSearch and resultPortfoliosSearch[0]["shares"] == int(shares): # if you have it and you have exactly the same number of shares, just delete it from portfolio resultPortfoliosUpdate = db.execute( "DELETE FROM portfolios WHERE userID = :sessionid AND symbol = :symbol", sessionid=session["user_id"], symbol=symbol) if not resultPortfoliosUpdate: return apology("You don't own any shares of that stock") else: return apology("You don't have enough shares of that stock") # also insert it into history table resultHistory = db.execute("INSERT INTO history (userID, shares, symbol, price) VALUES(:userID, :shares, :symbol, :price)", userID=session["user_id"], shares=0 - int(shares), symbol=symbol, price=float(price)) if not resultHistory: return apology("Problem making a purchase. Please try again later.") # and update users table cash resultUsers = db.execute( "UPDATE users SET cash = cash + :cost WHERE id = :sessionid", cost=cost, sessionid=session["user_id"]) if not resultUsers: return apology("Problem updating your wallet. Please try again later.") # redirect to index return redirect("/") else: # get symbols resultSymbols = db.execute( "SELECT symbol FROM portfolios WHERE userID = :sessionid", sessionid=session["user_id"]) if not resultSymbols: return apology("You don't have any stocks to sell") return render_template("sell.html", symbols=resultSymbols)
def quote(): """Get stock quote.""" if request.method == "POST": if not request.form.get("symbol"): return apology("No stock name submitted.",400) stock_info = lookup(request.form.get("symbol")) if not stock_info: return apology("Could not find the stock",400) stock_info["price"] = usd( stock_info["price"] ) return render_template("showQuote.html",stock_info=stock_info) else: return render_template("quote.html")
def buy(): """Buy shares of stock""" if request.method == "POST": # form names = symbol, shares symbol = request.form.get("symbol") shares = request.form.get("shares") if not RepresentsInt(shares): return apology("You must enter a valid number of shares") if not symbol or not shares or int(shares) <= 0: return apology("You must enter a valid symbol and shares") quote = lookup(symbol) if not quote: return apology("Not a valid symbol or API not working") walletrow = db.execute( "SELECT * FROM users WHERE id = :sessionid", sessionid=session["user_id"]) wallet = walletrow[0]["cash"] price = quote["price"] cost = float(price) * int(shares) if wallet < cost: return apology("Not enough cash in account") # if you can afford it, insert into history table resultHistory = db.execute("INSERT INTO history (userID, shares, symbol, price) VALUES(:userID, :shares, :symbol, :price)", userID=session["user_id"], shares=int(shares), symbol=symbol, price=float(price)) if not resultHistory: return apology("Problem making a purchase. Please try again later.") # look for in and then update portfolios resultPortfoliosSearch = db.execute( "SELECT shares FROM portfolios WHERE userID = :sessionid AND symbol = :symbol", sessionid=int(session["user_id"]), symbol=symbol) if resultPortfoliosSearch: # if you found it, update it resultPortfoliosUpdate = db.execute( "UPDATE portfolios SET shares = shares + :shares WHERE userID = :sessionid AND symbol = :symbol", sessionid=session["user_id"], symbol=symbol, shares=shares) if not resultPortfoliosUpdate: return apology("Error resultPortfoliosUpdate") else: resultPortfoliosAdd = db.execute("INSERT INTO portfolios (userID, shares, symbol) VALUES(:userID, :shares, :symbol)", userID=session["user_id"], shares=int(shares), symbol=symbol ) if not resultPortfoliosAdd: return apology("Error resultPortfoliosAdd") # and update users table cash resultUsers = db.execute( "UPDATE users SET cash = cash - :cost WHERE id = :sessionid", cost=cost, sessionid=session["user_id"]) if not resultUsers: return apology("Problem updating your wallet. Please try again later.") # redirect to index return redirect("/") else: return render_template("buy.html")
def sell(): """Sell shares of stock""" DBcash = db.execute( "SELECT cash FROM users WHERE id = :Uid", Uid = session["user_id"] ) TOTAL_SUM = DBcash[0]['cash'] DBcash[0]['cash'] = usd(DBcash[0]['cash']) M = sumStocks(session["user_id"]) N = {} #print(M) for stock in M: if M[stock]['amount'] > 0: N[stock] = M[stock] #print(N) if request.method == "POST": #print("Sell Post") if not request.form.get("symbol"): return apology("No stock name submitted.",400) if not request.form.get("shares"): return apology("No stock amount submitted.",400) try: a = int(request.form.get("shares")) except: return apology("invalid amount of shares.",400) #if (int(request.form.get("shares")) != int(request.form.get("shares"))//1) or int(request.form.get("shares")) < 0: if (int(request.form.get("shares")) != int(request.form.get("shares"))//1) or int(request.form.get("shares")) < 0: return apology("invalid amount of shares.",400) stock_info = lookup(request.form.get("symbol")) if not stock_info: return apology("Could not find the stock",400) if request.form.get("symbol") in M: if M[request.form.get("symbol")]['amount'] >= int(request.form.get("shares")): tot_price = stock_info["price"] * int(request.form.get("shares")) result = db.execute("INSERT INTO transactions (symbol,price,amount,date,Uid) VALUES(:symbol,:price,:amount, :date,:Uid)", symbol=stock_info["symbol"], price=stock_info["price"], amount=-int(request.form.get("shares")), date=datetime.now(), Uid=session["user_id"] ) if not result: return apology("The transaction could not be completed.") else: db.execute("UPDATE users SET cash = cash + :tot_price where id = :Uid", tot_price = tot_price, Uid = session["user_id"]) else: return apology("Not enuff shares to sell.",400) # TODO: write code... return redirect("/") #return render_template("sell.html",DBstocks=M) else: #print("Sell else") return render_template("sell.html",DBstocks=N)
def buy(): """Buy shares of stock""" if request.method == "GET": return render_template("buy.html") if request.method == "POST": # symbol err if not request.form.get("symbol"): return apology("must provide symbol") elif lookup(request.form.get("symbol")) == None: return apology("stock not found") # shares empty err if request.form.get("shares") == None: return apology("must provide number of shares") # set vars stock_temp = request.form.get("symbol") stock_temp = stock_temp.upper() stock = lookup(stock_temp) shares = request.form.get("shares") # shares format err if not shares.isdigit(): return apology("shares should be a whole number") elif int(shares) <= 0: return apology("buy at least one share") shares = int(shares) quote = stock.get("price") # quote = int(quote) # quote = usd(quote) cash = db.execute("SELECT cash FROM users WHERE id = (?)", session["user_id"]) balance = cash[0]["cash"] # balance = int(balance) # balance = usd(balance) # print(balance) time = datetime.now() total = shares * quote if balance < total: return apology("not enough energy") else: # transaction_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, # symbol TEXT NOT NULL, # quote INTEGER NOT NULL, # shares INTEGER NOT NULL, # total INTEGER NOT NULL, # time DATETIME NOT NULL, # u_id INTEGER NOT NULL, # FOREIGN KEY(u_id) REFERENCES users(id)); balance -= total balance = round(balance, 2) symbol = stock.get("symbol") name = stock.get("name") db.execute( "INSERT INTO history (symbol, name, quote, shares, total, time, u_id) VALUES(?, ?, ?, ?, ?, ?, ?)", symbol, name, quote, shares, total, time, session["user_id"]) db.execute("UPDATE users SET cash = (?) WHERE id = (?)", balance, session["user_id"]) flash( "({}) Successfully bought {} shares of {} at a price of {}\nCurrent balance: {}" .format(time, shares, symbol, quote, balance)) return redirect("/")
def sell(): """Sell shares of stock""" # get all fields for each stock the users own owned_stocks = db.execute("SELECT * FROM portfolio WHERE id = :userid", userid=session["user_id"]) if request.method == "POST": if not request.form.get("symbol"): # check for empty symbol return apology("You need to pick a symbol!") elif not request.form.get("shares"): return apology("You need to provide the number of shares to sell!") elif int( request.form.get("shares") ) <= 0: # technically useless because input form already specify must be integer return apology("Shares must be positive integers!") # extract no. of shares from portfolio owned_shares = db.execute( "SELECT * FROM portfolio WHERE symbol = :symbol AND id = :userid", symbol=request.form.get("symbol"), userid=session["user_id"]) # check if have enough shares if owned_shares[0]["shares"] < int(request.form.get("shares")): return apology("You do not have that many shares in that company!") # if have enough, UPDATE portfolio with new_owned_shares new_owned_shares = owned_shares[0]["shares"] - int( request.form.get("shares")) # find correct row in portfolio and update cash value db.execute( "UPDATE portfolio SET shares = :new_owned_shares WHERE symbol = :symbol AND id = :userid", new_owned_shares=new_owned_shares, symbol=request.form.get("symbol"), userid=session["user_id"]) # calculate new cash in hand value quote = lookup(request.form.get("symbol")) current_price = quote["price"] needed_shares = int(request.form.get("shares")) add_in_cash = current_price * needed_shares old_cash = db.execute("SELECT * FROM users WHERE id = :userid", userid=session["user_id"]) new_cash = old_cash[0]["cash"] + add_in_cash # UPDATE users table db.execute("UPDATE users SET cash = :new_cash WHERE id = :userid", new_cash=new_cash, userid=session["user_id"]) # insert sold transaction into history table time = str(datetime.datetime.now()).split('.')[0] db.execute( "INSERT INTO history (soldbuy, symbol, price, shares, time, id) VALUES ('Sold', :symbol, :price, :shares, :time, :id)", symbol=quote["symbol"], price=current_price, shares=needed_shares, time=time, id=session["user_id"]) return redirect("/") else: return render_template("sell.html", owned_stocks=owned_stocks) return apology("TODO")
def buy(): """Buy shares of stock""" if request.method == "GET": return render_template("buy.html") else: # ensure symbol exist stock = lookup(request.form.get("symbol")) if not stock: return apology("Invalid Symbol") # ensure number of shares is positive try: shares = int(request.form.get("shares")) if shares < 0: return apology("Shares must be a positive integer") except: return apology("Shares must be a positive integer") # check if user has enough money to buy money = db.execute("SELECT cash FROM users WHERE id= :id", id=session["user_id"]) if not money or float(money[0]["cash"]) < stock["price"] * shares: return apology("Not enough money") # update history db.execute("INSERT INTO histories (symbol, shares, price, id) \ VALUES (:symbol, :shares, :price, :id)", symbol=stock["symbol"], shares=shares, price=usd(stock["price"]), id=session["user_id"]) # update user cash db.execute("UPDATE users SET cash = cash - :purchase WHERE id = :id", id=session["user_id"], purchase=stock["price"] * float(shares)) # select user shares of that symbol user_shares = db.execute("SELECT shares FROM portfolio \ WHERE id = :id AND symbol = :symbol", id=session["user_id"], symbol=stock["symbol"]) # if it's a new investment, create new stock object if not user_shares: db.execute( "INSERT INTO portfolio (name, shares, price, total, symbol, id) \ VALUES (:name, :shares, :price, :total, :symbol, :id)", name=stock["name"], shares=shares, price=usd(stock["price"]), total=usd(shares * stock["price"]), symbol=stock["symbol"], id=session["user_id"]) # otherwise, increment shares count + update portfolio else: shares_total = user_shares[0]["shares"] + shares db.execute("UPDATE portfolio SET shares = :shares \ WHERE id = :id AND symbol = :symbol", shares=shares_total, id=session["user_id"], symbol=stock["symbol"]) # return to index return redirect(url_for("index"))
def articles(): """Look up articles for geo.""" articles = lookup(request.args.get("geo")) # TODO return jsonify(articles)
def sell(): """Sell shares of stock""" # User reached route via POST (as by submitting a form via POST) if request.method == "POST": quantity = int(request.form.get("shares")) symbol = lookup(request.form.get("symbol"))['symbol'] price = lookup(symbol)['price'] # Get data from DB available = db.execute( "SELECT quantity FROM stocks WHERE user_id = ? AND symbol = ?", session["user_id"], symbol) # Validate symbol if not symbol: return apology("symbol not found", 400) # Validate quantity if not quantity: return apology( "must provide valid number of stocks owned (integer)", 400) # Calculate users quantity of stocks after sell quantity_after = available[0]['quantity'] - quantity if quantity_after == 0: db.execute("DELETE FROM stocks WHERE user_id = ? AND symbol = ?", session["user_id"], symbol) elif quantity_after < 0: return apology("you're trying to sell more than you own", 400) else: # Update with new value db.execute( "UPDATE stocks SET quantity = ? WHERE user_id = ? AND symbol = ?", quantity_after, session["user_id"], symbol) # Calculate users cash after sell cash = db.execute("SELECT cash FROM users WHERE id = ?", session["user_id"])[0]['cash'] cash_after = cash + (price * quantity) db.execute("UPDATE users SET cash = ? WHERE id = ?", cash_after, session["user_id"]) # Register transaction in transactions table db.execute( "INSERT INTO transactions(user_id, action, symbol, quantity, price, date) VALUES (?, ?, ?, ?, ?, ?)", session["user_id"], "sold", symbol, quantity, price, datetime.now().strftime("%Y-%m-%d %H:%M:%S")) # Redirect user to home page flash("Transaction successful") return redirect("/") # User reached route via GET (as by clicking a link or via redirect) else: # Pass from DB to select menu what user has for sell rows = db.execute( "SELECT symbol, quantity FROM stocks WHERE user_id = ?", session["user_id"]) stocks = {} for row in rows: stocks[row['symbol']] = row['quantity'] return render_template("sell.html", stocks=stocks)
def buy(): """Buy shares of stock""" if request.method == "GET": return render_template("buy.html") else: symbol = request.form.get("symbol") shares = request.form.get("shares") try: shares = int(shares) except ValueError: return apology("Invalid quantity requested") else: if symbol == None: return apology("Unrecognized stock symbol") elif shares < 0: return apology("No refunds. Negative value entered") else: stock = lookup(symbol) if lookup(symbol) == None: return apology("Stock symbol not found") # calculate total stock cost cost = shares * lookup(symbol)["price"] # check cash in user's wallet cash = db.execute("SELECT cash FROM users WHERE \ id=:user_id;", user_id=session["user_id"]) # calculate balance after purchase balance = cash[0]["cash"] - cost if balance < 0: return apology("Insufficient funds.") else: # update history of transactions db.execute("INSERT INTO transactions (symbol, shares, price, id) \ VALUES(:symbol, :shares, :price, :user_id)", \ symbol=stock["symbol"], shares=shares, \ price=usd(stock["price"]), user_id=session["user_id"]) # update cash in users db.execute("UPDATE users SET cash = cash - :purchase WHERE id=:user_id", \ user_id=session["user_id"], purchase=stock["price"] * shares) # calculate number of shares owned owned = db.execute("SELECT shares, total FROM portfolio WHERE id=:user_id \ AND symbol=:symbol", user_id=session["user_id"], \ symbol=stock["symbol"]) if owned: # update shares in portfolio total_shares = owned[0]["shares"] + shares total_dec = Decimal(owned[0]["total"].strip('$')) total_value = float(total_dec) + cost db.execute("UPDATE portfolio SET shares=:shares, total=:total \ WHERE id=:user_id AND symbol=:symbol", \ shares=total_shares, total=total_value, \ user_id=session["user_id"], symbol=stock["symbol"]) else: # add portfolio record of stock db.execute("INSERT INTO portfolio (name, shares, price, total, symbol, id) \ VALUES(:name, :shares, :price, :total, :symbol, :user_id)", \ name=stock["name"], shares=shares, price=usd(stock["price"]), \ total=usd(shares * stock["price"]), symbol=stock["symbol"], \ user_id=session["user_id"]) # Redirect user to home page return redirect("/")
def sell(): """Sell shares of stock""" # get two rows, first for one sell operations, second for condition checking, containing stocks and their shares rows = db.execute( "SELECT stock, SUM(shares) as sumshares FROM portfolio WHERE id = :currentid GROUP BY stock HAVING sumshares > 0", currentid=session["user_id"]) # returns form if method is GET if request.method == "GET": # Checks if there are no stocks to sell if len(rows) == 0: return apology("No stocks to sell.") return render_template("sell.html", htmlrows=rows) # if form is submitted, sells it after checking for things elif request.method == "POST": # Checks if shares field was left blank if not request.form.get("shares"): return apology("Please enter number of shares you want to sell.") # Checks if submitted shares is positive and less than or equal to shares in portfolio for i in range(len(rows)): if rows[i]["stock"] == request.form.get("symbol"): if int(request.form.get("shares")) < 0: return apology("Please enter a positive number.") elif int(request.form.get("shares")) > rows[i]["sumshares"]: return apology("Not enough shares.") # Looks up a stock lookupstock = lookup(request.form.get("symbol")) # Declare values to be submitted into portfolio submittedstock = request.form.get("symbol") submittedshares = -int(request.form.get("shares")) positivesubmittedshares = int(request.form.get("shares")) currentstock = lookup(submittedstock) # Logs shares submitted as a negative quantity in portfolio, along with stock symbol result = db.execute( "INSERT INTO portfolio (id, stock, shares, price) VALUES(:_id, :_stock, :_shares, :_price)", _id=session["user_id"], _stock=submittedstock, _shares=submittedshares, _price=currentstock["price"]) if not result: return apology("Could not insert into database.") # Updates cash of the user cashlist = db.execute("SELECT cash FROM users WHERE id = :currentid", currentid=session["user_id"]) cash = cashlist[0]["cash"] cash += positivesubmittedshares * currentstock["price"] result2 = db.execute( "UPDATE users SET cash = :_cash WHERE id = :currentid", _cash=cash, currentid=session["user_id"]) # Send "Transaction Complete!" message via html file return redirect("/")
def sell(): """Sell shares of stock""" """HINT: When requested via GET, should display form to sell a stock.""" """HINT: When form is submitted via POST, sell the specified number of shares of stock, and update the user's cash.""" if request.method == "POST": # Check if the user entered a valid stock if not request.form.get("symbol"): return apology("missing symbol", 400) # Check if the user has entered a valid number elif not request.form.get("shares"): return apology("missing shares", 400) # Lookup symbol for the latest stock information stock = lookup(request.form.get("symbol")) # Store the number of shares the user would like to sell num_shares = int(request.form.get("shares")) # Check how many shares the user has of that particular stock port_rows = db.execute( "SELECT * FROM portfolio WHERE user_id = :user_id AND symbol = :symbol", user_id=session["user_id"], symbol=stock["symbol"]) # Store the number of shares the user owns into a variable called count count = port_rows[0]["shares"] # If the user does not have enough shares, return an apology if count < num_shares: return apology("too many shares", 400) # Insert the transaction into the transactions table db.execute( "INSERT INTO transactions (user_id, symbol, trans_qty, trans_indiv_price, timestamp) VALUES (:user_id, :symbol, :trans_qty, :trans_indiv_price, :timestamp)", user_id=session["user_id"], symbol=stock["symbol"], trans_qty=-1 * num_shares, trans_indiv_price=stock["price"], timestamp=datetime.now()) # Calculate the new number of shares the user owns shares = count - num_shares # Update the portfolio table db.execute("UPDATE portfolio SET shares=:shares WHERE symbol=:symbol", shares=shares, symbol=stock["symbol"]) # Delete the row if the number of shares now held is zero (0) if shares == 0: db.execute( "DELETE FROM portfolio WHERE user_id=:user_id & shares=0", user_id=session["user_id"]) # Check how much cash the user has user_rows = db.execute("SELECT * FROM users WHERE id = :id", id=session["user_id"]) cash = user_rows[0]["cash"] # Calculate the amount the user now has in cash new_cash = cash + stock["price"] * num_shares # Update the users table db.execute("UPDATE users SET cash=:cash WHERE id=:id", id=session["user_id"], cash=new_cash) flash("Sold!") return redirect("/") else: # Query database to see what stocks the user owns rows = db.execute( "SELECT * FROM portfolio WHERE user_id = :user_id ORDER BY symbol", user_id=session["user_id"]) return render_template("sell.html", rows=rows)
def articles(): """Look up articles for geo.""" geo = request.args.get("geo") articles = lookup(geo) return jsonify(articles)
def articles(): ##DONE! """Look up articles for geo.""" geo = request.args.get("geo") ###I changed to string. articles = lookup(geo) return jsonify([articles])
def buy(): if request.method == "GET": return render_template("buy.html") else: capital = db.execute("SELECT cash FROM users WHERE id=:userid", userid=session["user_id"]) if request.form.get("symbol") == None: return apology("Symbol required") elif request.form.get("shares") == None: return apology("Invalid quantity") elif lookup(request.form.get("symbol")) == None: return apology("Invalid symbol") elif capital[0]["cash"] < lookup(request.form.get( "symbol"))["price"] * int(request.form.get("shares")): return apology("Insufficient funds") else: today = date.today() d = today.strftime("%d/%m/%Y") now = datetime.now() current_time = now.strftime("%H:%M:%S") response = lookup(request.form.get("symbol")) amount = response["price"] * int(request.form.get("shares")) response = lookup(request.form.get("symbol")) trade = db.execute( "INSERT INTO transactions (userid,date,time,symbol,name,price,quantity,total) VALUES (:userid,:date,:time,:symbol,:name,:price,:quantity,:total)", userid=session["user_id"], date=d, time=current_time, symbol=request.form.get("symbol"), name=response["name"], price=response["price"], quantity=request.form.get("shares"), total=amount) update = db.execute("UPDATE users SET cash=:amt WHERE id=:userid ", amt=capital[0]["cash"] - amount, userid=session["user_id"]) check = db.execute( "SELECT symbol FROM holdings WHERE symbol=:symbol AND userid=:userid", symbol=request.form.get("symbol"), userid=session["user_id"]) if len(check) < 1: update_holdings = db.execute( "INSERT INTO holdings (userid,symbol,name,quantity) VALUES (:userid,:symbol,:name,:quantity)", userid=session["user_id"], symbol=request.form.get("symbol"), name=lookup(request.form.get("symbol"))["name"], quantity=request.form.get("shares")) else: quant = db.execute( "SELECT quantity FROM holdings WHERE userid=:userid AND symbol=:symbol ", userid=session["user_id"], symbol=request.form.get("symbol")) update_holdings = db.execute( "UPDATE holdings SET quantity=:q WHERE symbol=:symbol AND userid=:userid", q=int(quant[0]["quantity"]) + int(request.form.get("shares")), symbol=request.form.get("symbol"), userid=session["user_id"]) flash('Bought!') return redirect("/")
def sell(): """Sell shares of stock""" # User reached route via POST (as by submitting a form via POST) if request.method == "POST": quote = lookup(request.form.get("symbol")) # Ensure symbol was submitted if quote == None: return apology("must provide symbol", 403) # Ensure number of shares was submitted if not request.form.get("shares"): return apology("must provide a number of shares", 403) # Check if shares was a positive integer try: shares = int(request.form.get("shares")) except: return apology("shares must be a positive integer", 400) # Check if # of shares requested was 0 if shares <= 0: return apology("can't buy less than or 0 shares", 400) current_price = quote["price"] stock_name = quote["name"] symbol = quote["symbol"] stocks = db.execute( "SELECT SUM(shares) FROM transactions WHERE user_id = :user_id AND symbol = :symbol GROUP BY symbol", user_id=session["user_id"], symbol=symbol) user_id = session["user_id"] nb_shares = int(stocks[0]["SUM(shares)"]) rows = db.execute("SELECT cash FROM users WHERE id = :user_id", user_id=user_id) cash_remaining = rows[0]["cash"] if shares > nb_shares: return apology("not enough shares") total_price = shares * current_price # update table in the database and insert transactions db.execute("UPDATE users SET cash = cash + :price WHERE id = :user_id", price=total_price, user_id=session["user_id"]) db.execute( "INSERT INTO transactions (user_id, symbol, shares, price_per_share, stock_name, total_price) VALUES(:user_id, :symbol, :shares, :price, :name, :total_price)", user_id=session["user_id"], symbol=symbol, shares=-shares, price=current_price, name=stock_name, total_price=total_price) flash("Sold!") return redirect("/") # User reached route via GET (as by clicking a link or via redirect) else: stocks = db.execute( "SELECT symbol FROM transactions WHERE user_id = :user_id GROUP BY symbol HAVING SUM(shares) > 0", user_id=session["user_id"]) return render_template("sell.html", stocks=stocks)
def sell(): """Sell shares of stock""" if request.method == "GET": stocks = [] # lines = db.execute portfolio = db.execute( "select symbol as symbol, sum(shares) as shares from history where u_id = (?) group by symbol", session["user_id"]) for stock in portfolio: stocks.append(stock.get("symbol")) return render_template("sell.html", stocks=stocks) if request.method == "POST": if not request.form.get("shares"): return apology("shares unstated") stock_tosell = request.form.get("symbol") shares_tosell = request.form.get("shares") shares_current = db.execute( "select sum(shares) as shares from history where symbol = (?) and u_id = (?)", stock_tosell, session['user_id']) shares_current = int(shares_current[0]["shares"]) if not shares_tosell.isdigit() or int(shares_tosell) < 1: return apology("incorrect shares format") elif int(shares_tosell) > shares_current: return apology("selling more than is owned") shares_tosell = int(shares_tosell) # stock_tosell = request.form.get("symbol") cash = db.execute("select cash from users where id = (?)", session['user_id']) balance = cash[0]['cash'] stock_current = lookup(stock_tosell) quote = stock_current.get("price") total = shares_tosell * quote balance += total time = datetime.now() shares_tosell = 0 - shares_tosell # symbol TEXT NOT NULL, # quote INTEGER NOT NULL, # shares INTEGER NOT NULL, # total INTEGER NOT NULL, # time DATETIME NOT NULL, # u_id INTEGER NOT NULL, balance = round(balance, 2) # print(balance) db.execute("update users set cash = (?) where id = (?)", balance, session['user_id']) db.execute( "insert into history (symbol, quote, shares, total, time, u_id) values(?, ?, ?, ?, ?, ?)", stock_tosell, quote, shares_tosell, total, time, session['user_id']) flash( "({}) Successfully sold {} shares of {} at a price of {}\nCurrent balance: {}" .format(time, -shares_tosell, stock_tosell, quote, balance)) return redirect("/")
def buy(): """Buy shares of stock""" if request.method == "POST": shares = request.form.get("shares") quote = lookup( request.form.get("symbol").upper()) # lookup upper case of symbol if not request.form.get("symbol"): return apology("Symbol missing!") elif quote == None: return apology("404 stock not found!") elif not request.form.get("shares"): return apology("Number of shares missing!") elif not (shares.isnumeric()): # return apology if non numeric shares return apology("Shares must be numbers!") elif int(shares) <= 0 or ( int(shares) % 1 != 0): # return apology if -ve / fractional shares return apology("Invalid input for shares!") cash_dictionary = db.execute( "SELECT cash FROM users WHERE id = :userid", userid=session["user_id"] ) # use cash_dictionary to retrieve user's cash in dictionary var type cash = cash_dictionary[0][ 'cash'] # supposedly, get the cash value from dictionary cash_dictionary price = quote["price"] needed_shares = int(request.form.get("shares")) if cash < price * needed_shares: # check if have enough money return apology("Money is not enough!!!") new_cash = cash - (price * needed_shares) # remaining cash rows = db.execute( "SELECT * FROM portfolio WHERE id = :userid AND symbol = :stocksymbol", userid=session["user_id"], stocksymbol=quote["symbol"]) if len(rows) == 0: # if this user's have not bought this stock before # add a new row into table portfolio, setting initial value of column "symbol" too db.execute( "INSERT INTO portfolio (id, symbol, shares) VALUES (:userid, :stocksymbol, :shares)", userid=session["user_id"], stocksymbol=quote["symbol"], shares=needed_shares) else: # if user already holds shares in this stock # update table to add needed_shares into the value of column "shares" db.execute( "UPDATE portfolio SET shares = (shares + :addshares) WHERE id = :userid AND symbol = :symbol", addshares=needed_shares, userid=session["user_id"], symbol=quote["symbol"]) # update column "cash" in table users to remaining cash value db.execute("UPDATE users SET cash = :new_cash WHERE id = :userid", new_cash=new_cash, userid=session["user_id"]) # insert buy transaction into table history time = str(datetime.datetime.now()).split('.')[0] db.execute( "INSERT INTO history (soldbuy, symbol, price, shares, time, id) VALUES ('Buy', :symbol, :price, :shares, :time, :id)", symbol=quote["symbol"], price=price, shares=needed_shares, time=time, id=session["user_id"]) return redirect("/") else: return render_template("buy.html")
def buy(): c_username = request.cookies.get('c_username') c_logged_in = request.cookies.get('c_logged_in') c_cash = request.cookies.get('c_cash') c_user_id = request.cookies.get('c_user_id') g.c_logged_in = c_logged_in g.c_cash = c_cash if c_logged_in == 'True': if request.method == "POST": symbol = request.form.get("symbol") someshares = request.form.get("shares") if someshares != '': shares = int(someshares) else: shares = None if shares == None: flash("Please enter the number of shares", "danger") return redirect("/buy") elif shares == 0: flash("Please enter the number of shares", "danger") return redirect("/buy") else : company_data = lookup(symbol) # if company exists eg helper.py->lookup() will return none if company is not found if company_data == None: flash("Company not found", "danger") return redirect("/buy") else: price = company_data["price"] symbol = company_data["symbol"] name = company_data["name"] total_cost = float(price) * float(shares) user_data = users.query.filter_by(id = c_user_id).all() if user_data[0].cash > total_cost: # Deduct the cash from the account user_data[0].cash = float(user_data[0].cash) - total_cost #moved set cookie to end of function # Add the log for the transaction data = transactions( c_user_id,symbol,name,"BOUGHT",shares,price,datetime.datetime.now() ) db.session.add(data) db.session.commit() # Add or update the portfolio users_stock = users_stocks.query.filter_by(user_id = c_user_id, stock_symbol = symbol).all() # print(str(users_stock[0].stock_quantity)) if len(users_stock) == 1: print("Buying more" + str(shares)+" shares") users_stock[0].stock_quantity = users_stock[0].stock_quantity + shares db.session.commit() print("bought") if len(users_stock) == 0: print("you dont yet own the stock") stock = users_stocks( c_user_id,symbol,shares ) db.session.add(stock) db.session.commit() if shares == 1: flash("You successfully bought a share in " + symbol, "success") else: flash("You successfull bought " + str(shares) + " shares in " + symbol, "success") else: flash("You don't have enough money in your account","danger") return redirect("/buy") #Set cash cookie and return to homescreen resp = make_response(redirect("/")) c = float(c_cash) - total_cost resp.set_cookie('c_cash',str(c)) return resp else: return render_template("buy.html") else: return redirect("/login")
def buy(): """Buy shares of stock""" """HINT: When requested via GET, should display form to buy a stock.""" """HINT: When form is submitted via POST, purchase the stock so long as the user can afford it.""" if request.method == "POST": # Ensure a stock symbol was submitted if not request.form.get("symbol"): return apology("missing symbol", 400) elif not request.form.get("shares"): return apology("missing shares", 400) # store the number of shares the user would like to purchase num_shares = int(request.form.get("shares")) # Lookup symbol stock = lookup(request.form.get("symbol")) # Ensure stock symbol is valid if stock == None: return apology("invalid symbol", 400) # Check how much cash the user has user_rows = db.execute("SELECT * FROM users WHERE id = :id", id=session["user_id"]) cash = user_rows[0]["cash"] # Check if the user has enough cash to purchase the amount of shares for that particular stock if cash < stock["price"] * num_shares: return apology("can't afford", 400) # Insert the transaction into the transactions table db.execute( "INSERT INTO transactions (user_id, symbol, trans_qty, trans_indiv_price, timestamp) VALUES (:user_id, :symbol, :trans_qty, :trans_indiv_price, :timestamp)", user_id=session["user_id"], symbol=stock["symbol"], trans_qty=num_shares, trans_indiv_price=stock["price"], timestamp=datetime.now()) # Calculate remaining cash remaining = cash - stock["price"] * num_shares # Update the users table to reflect the amount of cash the user now has db.execute("UPDATE users SET cash=:cash WHERE id=:id", id=session["user_id"], cash=remaining) # Update the portfolio table to reflect the user's portfolio # Query database if the user already owns the stock port_rows = db.execute( "SELECT * FROM portfolio WHERE user_id = :user_id AND symbol = :symbol", user_id=session["user_id"], symbol=stock["symbol"]) # If the user doesn't already own that stock, create a new row if len(port_rows) == 0: db.execute( "INSERT INTO portfolio (user_id, symbol, name, shares) VALUES (:user_id, :symbol, :name, :shares)", user_id=session["user_id"], symbol=stock["symbol"], name=stock["name"], shares=num_shares) # If the user already owns the stock, update the existing row else: # Query database for count of existing shares count = port_rows[0]["shares"] db.execute("UPDATE portfolio SET shares=:shares", shares=count + num_shares) flash("Bought!") return redirect("/") else: return render_template("buy.html")
def sell(): """Sell shares of stock""" # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure symbol was submitted if not request.form.get("symbol"): return apology("must provide symbol", 403) # Ensure shares was submitted if not request.form.get("shares"): return apology("must provide shares", 403) # Remember the symbol and shares symbol = request.form.get("symbol") shares = int(request.form.get("shares")) # Query database for the number of shares of the entered symbol owned by the user ownedShares = int( db.execute( "SELECT SUM(shares) AS shares FROM history WHERE id = :id AND symbol = :symbol GROUP BY symbol", id=session["user_id"], symbol=symbol)[0]["shares"]) # Ensure valid shares if shares > ownedShares: return apology("too many shares", 403) # Lookup for current price price = lookup(symbol)["price"] # Calculate selling price total = shares * price # Record transaction db.execute( "INSERT INTO history (id, symbol, shares, price, timestamp) VALUES (:id, :symbol, :shares, :price, :timestamp)", id=session["user_id"], symbol=symbol, shares=-shares, price=price, timestamp=datetime.now()) # Query database for available cash cash = float( db.execute("SELECT cash FROM users WHERE id = :id", id=session["user_id"])[0]["cash"]) # Update database db.execute("UPDATE users SET cash = :cash WHERE id = :id", cash=cash + total, id=session["user_id"]) # Redirect user to index page return redirect("/") # User reached route via GET (as by clicking a link or via redirect) else: # Query database for the user's stocks rows = db.execute( "SELECT symbol FROM history WHERE id = :id GROUP BY symbol", id=session["user_id"]) return render_template("sell.html", rows=rows)
def sell(db): # Query database for user's transaction summary rows = db.execute( "SELECT symbol, SUM(shares) AS shares FROM transactions WHERE user_id = :id GROUP BY symbol", id=session["user_id"]) if request.method == "POST": # Ensure company symbol was submitted if not request.form.get("symbol"): return apology("must provide Company Symbol", 403) # Ensure number of shares was submitted if not request.form.get("shares"): return apology("must provide number of shares", 403) company = lookup(request.form.get("symbol")) # Ensure company exists if not company: return apology("company not found", 404) # Ensure that user ownes any shares of submitted company count = 0 for row in rows: if (request.form.get("symbol") == row["symbol"]): count = count + 1 if (count == 0): return apology( "you don't have any shares of " + request.form.get("symbol"), 404) # Ensure that submitted shres number is integer and within range between 1 and possesed number of shares submitted_shares = int(float(request.form.get("shares"))) if (submitted_shares < 1): return apology("number of shares has to be 1 or more", 403) for row in rows: if (request.form.get("symbol") == row["symbol"]): if (row["shares"] < submitted_shares): return apology("you can't sell more shares than you have", 403) price = float(company["price"]) value = price * submitted_shares # Query database for cash money = db.execute("SELECT cash FROM users WHERE id = :id", id=session["user_id"]) cash = money[0]["cash"] balance = cash + value # Insert transaction into database db.execute( "INSERT INTO transactions (user_id, symbol, price, shares, balance) VALUES (:user_id, :symbol, :price, :shares, :balance)", user_id=session["user_id"], symbol=company["symbol"], price=price, shares=(-1 * submitted_shares), balance=balance) # Update user's cash db.execute("UPDATE users SET cash = :balance WHERE id = :id", balance=balance, id=session["user_id"]) flash('Sold!') return redirect("/") else: for row in rows: # remove empty stocks from the list if row["shares"] == 0: rows.remove(row) return render_template("sell.html", rows=rows)
def articles(): """Look up articles for geo.""" #get the value of geo from the url #output the article objects as json data return jsonify(lookup(request.args.get("geo")))
def buy(): """Buy shares of stock""" # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Get data from input form symbol = lookup(request.form.get("symbol"))['symbol'] # Validate symbol if not symbol: return apology("symbol not found", 400) check = request.form.get("shares") if not check or not check.isdigit() or check == None: return apology("must provide valid number of stocks (integer)", 400) quantity = int(check) # Validate quantity if not quantity or quantity <= 0: return apology("must provide valid number of stocks (integer)", 400) # Calculating amount of cash for transaction price = lookup(symbol)['price'] cash = db.execute("SELECT cash FROM users WHERE id = ?", session["user_id"])[0]['cash'] cash_after = cash - price * quantity if cash_after < 0: return apology("not enough cash", 400) # Insert into stocks table or update row if user already has this stock user_stock = db.execute( "SELECT quantity FROM stocks WHERE user_id = ? AND symbol = ?", session["user_id"], symbol) if not user_stock: db.execute( "INSERT INTO stocks(user_id, symbol, quantity) VALUES (?, ?, ?)", session["user_id"], symbol, quantity) else: quantity = quantity + user_stock[0]['quantity'] db.execute( "UPDATE stocks SET quantity = ? WHERE user_id = ? AND symbol = ?", quantity, session["user_id"], symbol) # Calculate cash left db.execute("UPDATE users SET cash = ? WHERE id = ?", cash_after, session["user_id"]) # Register transaction in transactions table db.execute( "INSERT INTO transactions(user_id, action, symbol, quantity, price, date) VALUES (?, ?, ?, ?, ?, ?)", session["user_id"], "bought", symbol, quantity, price, datetime.now().strftime("%Y-%m-%d %H:%M:%S")) # Redirect user to home page flash("Transaction successful") return redirect("/") # User reached route via GET (as by clicking a link or via redirect) else: return render_template("buy.html")
response.headers["Expires"] = 0 response.headers["Pragma"] = "no-cache" return response db = SQL("sqlite:///mashup.db")@ app.route("/") def index(): "" "Render map." "" if not os.environ.get("API_KEY"): raise RuntimeError("API_KEY not set") return render_template("index.html", key = os.environ.get("API_KEY"))@ app.route("/articles") def articles(): geo = request.args.get("geo") if not geo: raise RuntimeError("Geo not set") articles = lookup(geo) if len(articles) > 5: return jsonify([articles[0], articles[1], articles[2], articles[4], articles[5]]) else : return jsonify(articles)@ app.route("/search") def search(): q = request.args.get("q") + "%" place = db.execute("SELECT * FROM places WHERE postal_code \ LIKE :q OR place_name LIKE :q OR admin_name1 LIKE :q", q = q) if len(place) > 10: return jsonify([place[0], place[1], place[2], place[3], place[4], place[5], place[6], place[7], place[8], place[9] ]) else : return jsonify(place)
def sell(): """Sell shares of stock""" if request.method == "GET": portfolio = db.execute("SELECT symbol FROM portfolio WHERE \ id=:user_id", user_id=session["user_id"]) return render_template("sell.html", portfolio=portfolio) else: symbol = request.form.get("symbol") shares = int(request.form.get("shares")) if not symbol: return apology("Select symbol") # ensure positive integer input if not shares or shares < 1: return apology("Enter a positive number of shares to sell") # query user portfolio user_stocks = db.execute("SELECT symbol, shares FROM portfolio WHERE \ id=:user_id AND symbol=:symbol", user_id=session["user_id"], \ symbol=symbol) # subtract quantity of shares from currently owned available = int(user_stocks[0]["shares"]) if available < shares: return apology("Insufficient shares") # update remaining shares available -= shares # lookup current value of share shareval = lookup(symbol)["price"] value = shareval * shares # query and update user balance userbal = db.execute("SELECT cash FROM users WHERE id=:user_id", \ user_id=session["user_id"]) balance = userbal[0]["cash"] balance += value # update user portfolio databse db.execute("UPDATE portfolio SET shares=:shares, price=:price, \ total=:balance WHERE id=:user_id AND symbol=:symbol", \ shares=available, price=shareval, balance=balance, \ user_id=session["user_id"], symbol=symbol) # remove stock record if no shares remain if available == 0: db.execute("DELETE FROM portfolio WHERE shares=0") # insert record into transactions database db.execute("INSERT INTO transactions (symbol, shares, price, id) \ VALUES(:symbol, :shares, :price, :user_id)", \ symbol=symbol, shares=shares, price=value, \ user_id=session["user_id"]) # update users database for cash (increase balance) db.execute("UPDATE users SET cash=:balance WHERE id=:user_id", \ user_id=session["user_id"], balance=balance) # Redirect user to home page return redirect("/")
def buy(): """Buy shares of stock""" if request.method == "POST": symbol = lookup(request.form.get("symbol")) if not symbol or symbol == None: return apology("Symbol not found", 403) if not request.form.get("shares"): return apology("Enter number o shares", 403) rows = db.execute("SELECT * FROM users WHERE id = :id", id=session["user_id"]) if float(rows[0]["cash"]) < (int(request.form.get("shares")) * float(symbol["price"])): return apology("Not enough cash", 403) else: cash = float(rows[0]["cash"]) - (int(request.form.get("shares")) * float(symbol["price"])) total = int(request.form.get("shares")) * float(symbol["price"]) db.execute("UPDATE users SET cash = :cash WHERE id = :id", cash=cash, id=session["user_id"]) db.execute( "INSERT INTO orders (order_by, share_name, shares_qty, share_price, purchase_total) VALUES (:by, :name, :qty, :price, :total)", by=session["user_id"], name=symbol["symbol"], qty=int(request.form.get("shares")), price=symbol["price"], total=total) # Handles index shares_owned_rows = db.execute( "SELECT owned_by, share_name, shares_qty FROM shares_owned WHERE owned_by = :id", id=session["user_id"]) # Make a list of share_name that are attached to the user share_name_list = [] for row in shares_owned_rows: share_name_list.append(row["share_name"]) if symbol["symbol"] in share_name_list: for row in shares_owned_rows: if row["share_name"] == symbol["symbol"]: new_qty = int(row["shares_qty"] + int(request.form.get("shares"))) db.execute( "UPDATE shares_owned SET shares_qty =:qty , holding =:hold WHERE share_name =:name", qty=new_qty, hold=float(new_qty * float(symbol["price"])), name=symbol["symbol"]) else: db.execute( "INSERT INTO shares_owned (owned_by, share_name, shares_qty, share_price, holding) VALUES (:by, :name, :qty, :price, :hold)", by=session["user_id"], name=symbol["symbol"], qty=int(request.form.get("shares")), price=symbol["price"], hold=total) return redirect("/") else: return render_template("buy.html")
def sell(): """Sell shares of stock""" if request.method == "GET": return render_template("sell.html") else: # ensure symbol exist stock = lookup(request.form.get("symbol")) if not stock: return apology("Invalid Symbol") # ensure number of shares is positive try: shares = int(request.form.get("shares")) if shares < 0: return apology("Shares must be a positive integer") except: return apology("Shares must be a positive integer") # select the shares of the stock user_shares = db.execute( "SELECT shares FROM portfolio WHERE id = :id AND symbol = :symbol", id=session["user_id"], symbol=stock["symbol"]) # check if enough shares to sell if not user_shares or int(user_shares[0]["shares"]) < shares: return apology( "You don't hold enough shares to sell that quantity") # update history db.execute("INSERT INTO histories (symbol, shares, price, id) \ VALUES (:symbol, :shares, :price, :id)", symbol=stock["symbol"], shares=-shares, price=usd(stock["price"]), id=session["user_id"]) # update user cash db.execute("UPDATE users SET cash = cash + :sale WHERE id = :id", id=session["user_id"], sale=stock["price"] * float(shares)) # decrease number of shares of the stock total_shares = user_shares[0]["shares"] - shares # if shares is zero, remove from portfolio if total_shares == 0: db.execute( "DELETE FROM portfolio WHERE id = :id AND symbol = :symbol", id=session["user_id"], symbol=stock["symbol"]) # else update portfolio shares else: db.execute( "UPDATE portfolio SET shares = :shares WHERE id = :id AND symbol = :symbol", shares=total_shares, id=session["user_id"], symbol=stock["symbol"]) # return to index return redirect(url_for("index"))
def sell(): """Sell shares of stock""" if request.method == "POST": # Получаем информацию об акции info = {} symbol = request.form.get("symbol") if not symbol: return apology("missing symbol", 400) info = lookup(symbol) price = info["price"] # Получаем количесво денег у пользователя cash = db.execute("SELECT cash FROM users WHERE id = :user_id", user_id = session["user_id"]) cash = cash.fetchall() cash = cash[0][0] #Получаем количество акций shares = request.form.get("shares") if not shares: return apology("MISSING SHARES", 400) shares = int(shares) share_old = db.execute("SELECT count FROM stock WHERE stock_id = :id", id = session["user_id"]) share_old = share_old.fetchall() share_old = share_old[0][0] if share_old < shares : return apology("TOO MANY SHARES", 400) # Вычисляем стоимость cost = price * shares # Прибавляем стоимость к деньгам пользователя cash += cost # Обновляем данные о деньгах db.execute("UPDATE users SET cash = :cash WHERE id = :id", id = session["user_id"], cash = cash) # Обновляем данные об акциях пользователя share_old -= shares db.execute("UPDATE stock SET count = :share WHERE stock_id = :id", id = session["user_id"], share = share_old) db.execute("DELETE FROM stock WHERE count = 0") return redirect("/") else: symbols = db.execute("SELECT stock_name FROM stock WHERE stock_id = :id", id = session["user_id"]) symbols = symbols.fetchall() return render_template("sell.html", stock = symbols)
def sell(): if request.method == 'GET': # Gets dict of stock tickers that user bought tickers = db.execute( "SELECT ticker FROM purchases WHERE id = ? GROUP BY ticker HAVING SUM(shares) > 0;", session["user_id"]) print(tickers) # List of stocks the user owns stocks = [] # Turns dict of tickers to list for i in range(0, len(tickers)): ticker = tickers[i]['ticker'] stocks.append(ticker.upper()) return render_template('sell.html', stocks=stocks) # After form submission if request.method == 'POST': # Checks that inputted quantity is a positive integer try: if int(request.form.get('shares').replace(',', '')) < 0: return apology("Please enter a valid quantity", 403) except: return apology("Please enter a positive integer as the quantity", 403) shares = int(request.form.get('shares').replace(',', '')) stock = request.form.get('stocks') # If user doesn't select a stock if not stock: return apology("Please select a stock to sell") # Dict of shares they own of the stock owned_shares = db.execute( 'SELECT SUM(shares) as num_shares FROM purchases WHERE id = ? AND ticker = ?', session["user_id"], stock) # Number of shares user owns of stock num_shares = int(owned_shares[0]['num_shares']) # If user doesn't own the stock if num_shares < 0: return apology('You do not own that stock') # If they don't have enough shares to sell the amount they entered. if num_shares < shares: return apology('Too many shares') # If user didn't input number of shares if not shares: return apology("Please enter a quantity of shares", 403) try: if int(shares) < 0: return apology("Please enter a valid quantity of shares", 403) except: return apology( "Please enter a positive integer as the quantity of shares", 403) # Stock, shares looked_ticker = lookup(stock) list_cash = db.execute("SELECT cash FROM users WHERE id = :id", id=session["user_id"]) cash = int(list_cash[0]['cash']) db.execute( "INSERT INTO purchases (id, ticker, price, date, shares, company_name) VALUES (?,?,?,?,?,?)", session['user_id'], stock.upper(), looked_ticker['price'], datetime.datetime.now(), shares * -1, looked_ticker['name']) db.execute("UPDATE users SET cash = ? WHERE id = ?", cash + int(looked_ticker['price']) * int(shares), session['user_id']) flash(f"You have sold {shares} shares of {stock.upper()}") return redirect("/")
def sell(): """Sell shares of stock""" user_id = session['user_id'] user_shares = db.execute( "SELECT transactions.stock_id, stocks.symbol, stocks.company_name, " "sum(transactions.shares) " "FROM transactions " "JOIN stocks " "ON stocks.id = transactions.stock_id " "WHERE user_id=:user_id " "GROUP BY stock_id", user_id=user_id) user_stocks = [] for stocks in user_shares: if stocks['sum(transactions.shares)'] > 0: user_stocks.append(stocks['symbol']) if request.method == "POST": stock_to_sell = request.form.get("symbol") shares_to_sell = request.form.get("shares") # Validate submitted stock to sell if not stock_to_sell: return apology("You must select stock name", 400) elif stock_to_sell is None: return apology("Sorry, no such a stock", 400) # Validate submitted shares if not shares_to_sell.isdigit(): return apology("You must provide positive integer", 400) else: shares_to_sell = int(shares_to_sell) # Validate if user has enough shares available to sell shares_available = db.execute("SELECT sum(transactions.shares) " "FROM transactions " "JOIN stocks " "ON stocks.id = transactions.stock_id " "WHERE user_id=:user_id " "AND symbol=:symbol ", user_id=user_id, symbol=stock_to_sell)[0]['sum(transactions.shares)'] if shares_to_sell > shares_available: return apology("Exceeded your amount of shares to sell", 400) # Shares quoted_to_sell = lookup(stock_to_sell) iex_symbol = quoted_to_sell['symbol'] iex_name = quoted_to_sell['name'] iex_price = quoted_to_sell['price'] shares_update = -shares_to_sell # Balance (cash) balance = db.execute("SELECT cash " "FROM users " "WHERE id = :user_id", user_id=user_id)[0]['cash'] cash_from_sell = shares_to_sell * iex_price balance_update = balance + cash_from_sell # Update db if transaction is valid if shares_to_sell <= shares_available: stock_db_id = db.execute("SELECT id " "FROM stocks " "WHERE symbol = ?", iex_symbol)[0]['id'] db.execute("INSERT INTO transactions (stock_id, user_id, shares, price) " "VALUES (?, ?, ?, ?)", stock_db_id, user_id, shares_update, iex_price) db.execute("UPDATE users " "SET cash= ? " "WHERE id= ? ", balance_update, user_id) return redirect("/") else: return render_template("sell.html", user_stocks=user_stocks)
def buy(): """Buy shares of stock""" if request.method == "POST": if not request.form.get("symbol"): return apology("must provide symbol") elif not request.form.get("shares"): return apology("must provide number of shares") shares = int(request.form.get("shares")) if shares < 1: return apology("must enter a number greater than 0") symbol = request.form.get("symbol") stock = lookup(symbol) if stock == None: return apology("Stock does not exist") rows = db.execute("SELECT cash FROM users WHERE id = :user_id", user_id=session["user_id"]) # How much $$$ the user still has in their account cash_remaining = rows[0]["cash"] price_per_share = stock["price"] # Calculate the price of requested shares total_price = price_per_share * shares if total_price > cash_remaining: return apology("you do not have enough cash to make this purchase") # select user shares of symbol user_shares = db.execute("SELECT shares FROM portfolio WHERE id = :id AND symbol = :symbol", \ id = session["user_id"], symbol = stock["symbol"]) db.execute("UPDATE users SET cash=:cash WHERE id=:id", cash=cash_remaining - total_price, id=session["user_id"]) #if user doesn't already have that stock then create a new object if not user_shares: db.execute("INSERT INTO portfolio (name, shares, price, total, symbol, id) \ VALUES(:name, :shares, :price, :total, :symbol, :id)" , \ name=stock["name"], shares= shares, price= price_per_share, \ total= usd(total_price), symbol= stock["symbol"], id= session["user_id"]) #if user already has it then increase number of shares else: shares_total = int(user_shares[0]["shares"]) + shares db.execute("UPDATE portfolio SET shares=:shares \ WHERE id=:id AND symbol=:symbol" , shares = shares_total, \ id=session["user_id"], symbol = stock["symbol"]) timestamp = datetime.datetime.now() db.execute("INSERT INTO transactions (id, symbol, name, shares, price, timestamp) \ VALUES (:id, :symbol, :name, :shares, :price, :timestamp)" , \ id = session["user_id"], symbol = stock["symbol"], name = stock["name"], shares = shares, price = price_per_share, timestamp = timestamp) return redirect("/") else: return render_template("buy.html")
def sell(): """Sell shares of stock""" if request.method == "POST": symbol = request.form.get("symbol") quote = lookup(symbol) shares = int(request.form.get("shares")) stock = db.execute( "SELECT * FROM portfolio WHERE symbol = :symbol AND id = :id", symbol=symbol, id=session["user_id"]) stock = db.execute( "SELECT SUM(shares) as total_shares FROM portfolio WHERE id = :id AND symbol = :symbol GROUP BY symbol", id=session["user_id"], symbol=request.form.get("symbol")) if stock[0]["total_shares"] < int(shares): return apology("you can't sell more than you own", 400) else: rows = db.execute("SELECT cash FROM users WHERE id = :user_id", user_id=session["user_id"]) cash = rows[0]["cash"] price_per_share = quote["price"] total_price = price_per_share * float(shares) # update user cash (increase) db.execute( "UPDATE users SET cash = :cash + :price WHERE id = :user_id", cash=cash, price=total_price, user_id=session["user_id"]) # decrement the shares count shares_total = stock[0]["total_shares"] - int(shares) # if after decrement is zero, delete shares from portfolio if shares_total == 0: db.execute("DELETE FROM portfolio \ WHERE id=:id AND symbol=:symbol" , \ id = session["user_id"], \ symbol = symbol) # otherwise, update portfolio shares count else: db.execute("UPDATE portfolio SET shares=:shares \ WHERE id=:id AND symbol=:symbol" , \ shares = shares_total, id = session["user_id"], \ symbol = symbol) name = db.execute( "SELECT name FROM portfolio WHERE id = :id AND symbol = :symbol", id=session["user_id"], symbol=symbol) timestamp = datetime.datetime.now() db.execute("INSERT INTO transactions (id, symbol, name, shares, price, timestamp) \ VALUES(:id, :symbol, :name, :shares, :price, :timestamp)" , \ symbol = symbol, shares = -shares, name = quote["name"], \ price = price_per_share, id = session["user_id"], timestamp = timestamp) # Redirect user to home page return redirect("/") else: stocks = db.execute( "SELECT symbol, SUM(shares) as total_shares FROM portfolio WHERE id = :id GROUP BY symbol HAVING total_shares > 0", id=session["user_id"]) return render_template("sell.html", stocks=stocks)
def sell(): c_logged_in = request.cookies.get('c_logged_in') c_cash = request.cookies.get('c_cash') c_user_id = request.cookies.get('c_user_id') g.c_logged_in = c_logged_in g.c_cash = c_cash if c_logged_in == 'True': _users_stocks = users_stocks.query.filter_by(user_id = c_user_id) if request.method == "POST": selling_stock = request.form.get("stock") #number_to_sell = int(request.form.get("number_to_sell")) n_sell = request.form.get("number_to_sell") if n_sell != '': number_to_sell = int(n_sell) else: number_to_sell = None if selling_stock == None: flash("Please select a stock to sell", "danger") return redirect("/sell") elif number_to_sell == None: flash("Please enter the number you would like to sell", "danger") return redirect("/sell") else: stock_owned = 0 user_stock_to_sell = users_stocks.query.filter_by(user_id = c_user_id).filter_by(stock_symbol = selling_stock ) print(user_stock_to_sell[0].stock_quantity) stock_quote = lookup(selling_stock) stock_price = stock_quote["price"] total_sale_price = stock_price * float(number_to_sell) if user_stock_to_sell[0].stock_quantity < number_to_sell: flash("You don't have that many to sell","danger") return redirect("/sell") else: ## Add to transactions data = transactions( c_user_id,stock_quote["symbol"],stock_quote["name"],"SOLD",number_to_sell,stock_price,datetime.datetime.now() ) db.session.add(data) # Change cash user_data = users.query.filter_by(id = c_user_id) user_data[0].cash = float(user_data[0].cash) + total_sale_price c_cash = float(c_cash) + total_sale_price g.c_cash = float(g.c_cash) + total_sale_price if user_stock_to_sell[0].stock_quantity > number_to_sell: user_stock_to_sell[0].stock_quantity = user_stock_to_sell[0].stock_quantity - number_to_sell elif user_stock_to_sell[0].stock_quantity == number_to_sell: user_stock_to_sell.delete() db.session.commit() flash("Stock sold successfully","success") #set the cookie resp = make_response(redirect("/")) resp.set_cookie('c_cash', str(c_cash)) return resp return render_template("sell.html", users_stocks=_users_stocks) else: return redirect("/login")
def buy(): """Buy shares of stock""" # User reached route via POST if request.method == 'POST': symbol = request.form.get("symbol").lower() # Ensure symbol is provided if not symbol: return apology("missing symbol", 400) shares = request.form.get("shares") # Ensure shares is provided if not shares: return apology("missing shares", 400) shares = int(shares) # Look up the stock stock_info = lookup(symbol) # Ensure stock is found if not stock_info: return apology("invalid symbol", 400) stock_price = stock_info["price"] stock_symbol = stock_info["symbol"] user_id = session["user_id"] # Query database for current user's cash cash = db.execute("SELECT cash FROM users WHERE id = :user_id", user_id=user_id)[0]["cash"] remain_cash = cash - stock_price * shares # Ensure user can afford the number of shares at the current price. if remain_cash < 0: return apology("can't afford", 400) # Update current user's cash in database db.execute("UPDATE users SET cash = :remain_cash WHERE id = :user_id", remain_cash=remain_cash, user_id=user_id) # Insert the transaction to table transactions in database db.execute(""" INSERT INTO transactions (symbol, shares, price, user_id) VALUES (:symbol, :shares, :price, :user_id) """, symbol=stock_symbol, shares=shares, price=stock_price, user_id=user_id) # Flash message flash("Bought!") # Redirect user to home page return redirect("/") # User reached route via GET else: return render_template("buy.html")