Skip to main content
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
deleted 44 characters in body
Source Link
JJuice
  • 119
  • 5

Here's my code for the buyindex application:

"""Buy shares ofdef stock"""
index():
# User reached route via"""Show POSTportfolio (asof bystocks"""
# submittingUser areached formpage via POST)redirect
if request.method == "POST""GET":

    # EnsureLookup stockusername symboland wascash submitted
of current user and ifstore notin request.form.get("symbol"):variables
       user return= apologydb.execute("Missing"SELECT stock'susername symbol",FROM 400)

users WHERE id = else:
        # Ensure float number ofuser_id", sharesuser_id was= submittedsession["user_id"])
        try:
  cash = db.execute("SELECT cash FROM users WHERE id = :user_id", sharesuser_id = float(request.form.get("shares")session["user_id"])

      # Lookup exceptcurrent ValueError:
portfolio of user and store in variable sumshares
    sumshares return= apologydb.execute("Please submit number"SELECT ofstock, shares"symbol, 400SUM(numshares)

  , price, valuestocks FROM portfolio WHERE #user_id Ensure= positive:user_id integerGROUP numberBY ofstock", sharesuser_id was= submittedsession["user_id"])
  
    # Define variable iffor (sharestotal %value 1)of !=all 0stocks orand (sharesinitialize <to 0):zero
            return apology("Please submit number oftotalvaluestocks shares",= 400)0

      # Update #sumshares Checkwith iflatest stock existsprices
      for i elifin (lookuprange(request.form.getlen("symbol"sumshares)) == None):
           sumshares[i]['price'] return= apologylookupindex("Stock does not exist", 400sumshares[i]['symbol'])
 
        else:
            # Check stock and store info in variables
          sumshares[i]['valuestocks'] = stocksumshares[i]['price'] =* lookup(request.form.getsumshares[i]['SUM("symbol")numshares)']
            stocknametotalvaluestocks = stock['name']
totalvaluestocks + sumshares[i]['valuestocks']

        # Update stockpriceto =format stock['price']USD
            stocksymbolsumshares[i]['price'] = stock['symbol']usd(sumshares[i]['price'])
            totalvaluesumshares[i]['valuestocks'] = usd(stockprice * sharessumshares[i]['valuestocks'])

      # Calculate grand total
   # Calculategrandtotal current= datecash[0]['cash'] and+ timetotalvaluestocks

    # format values to USD
    nowgrandtotal = datetime.nowusd(grandtotal)
            dcash[0]['cash'] = now.dateusd(cash[0]['cash'])
            ttotalvaluestocks = now.timeusd(totalvaluestocks)

            # Lookup user's available cash and storeGenerate inindex variablepage
       return render_template("index.html", user = user[0]['username'], user_cashcash = db.execute("SELECT cashcash[0]['cash'], FROMtotalvaluestocks users= WHEREtotalvaluestocks, idsumshares = :user_id"sumshares, user_idgrandtotal = session["user_id"]grandtotal)

     # User reached route via POST (as #by Ensuresubmitting usera hasform enoughvia cashPOST)
elif request.method == "POST":

    # Check for valid input
 if totalvalue > user_cash[0]['cash']try:
               extracash return= apologyfloat("Not enough cash to buy", 403request.form.get("extracash"))

           except elseValueError:
               return #apology("Please addtype transactionin tovalid thecash portfolioamount", table403)
     
    # Add cash to user
    resultcurrent = db.execute("INSERT INTO portfolio (user_id, stock, symbol, price, numshares, valuestocks, date, time, buyorsell) VALUES(:user_id, :stock,"SELECT :symbol,cash :price,FROM :numshares,users :valuestocks,WHERE :date,id :time,= :buyorsell)"user_id", user_id = session["user_id"], stock = stockname, symbol = stocksymbol, price = stockprice, numshares = shares, valuestocks = totalvalue, date = d, time = t, buyorsell = 'BUY')
 
                if result != None:
                    db.execute("UPDATE users SET cash = :cash WHERE id = :user_id", cash = user_cash[0]['cash']current[0]['cash'] -+ totalvalueextracash, user_id = session["user_id"])

                    # RedirectReturn user to index
                    flash('BUYhome SUCCESSFUL')page
                    return redirect("/")

# User reached route via GET (as by clicking a link or via redirect)
else:
    return render_template("buy.html")

Looking at the log file, there is a problem with the application trying to multiply two variables, one of which is of type 'NonType' and the other is an int. Since there is only one line of code in my whole program where I multiply two values, one of them being an int it should result from:

totalvaluesumshares[i]['valuestocks'] = (stockpricesumshares[i]['price'] * sharessumshares[i]['SUM(numshares)']

But given all the other earlier IF conditions I cannot see how either stockprice or shares can haveThis line of code is meant to update the value None and so is of typethe stock with the current price info. So instead of showing the historic price NonType(at time of purchase), it shows the current price.

In the buy section there is another multiplication, but that multiplication has no ints as input.

Here's my code for the buy application:

"""Buy shares of stock"""

# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":

    # Ensure stock symbol was submitted
    if not request.form.get("symbol"):
        return apology("Missing stock's symbol", 400)

    else:
        # Ensure float number of shares was submitted
        try:
            shares = float(request.form.get("shares"))

        except ValueError:
            return apology("Please submit number of shares", 400)

        # Ensure positive integer number of shares was submitted
        if (shares % 1) != 0 or (shares < 0):
            return apology("Please submit number of shares", 400)

        # Check if stock exists
        elif (lookup(request.form.get("symbol")) == None):
            return apology("Stock does not exist", 400)
 
        else:
            # Check stock and store info in variables
            stock = lookup(request.form.get("symbol"))
            stockname = stock['name']
            stockprice = stock['price']
            stocksymbol = stock['symbol']
            totalvalue = (stockprice * shares)

            # Calculate current date and time
            now = datetime.now()
            d = now.date()
            t = now.time()

            # Lookup user's available cash and store in variable
            user_cash = db.execute("SELECT cash FROM users WHERE id = :user_id", user_id = session["user_id"])

            # Ensure user has enough cash
            if totalvalue > user_cash[0]['cash']:
                return apology("Not enough cash to buy", 403)

            else:
                # add transaction to the portfolio table
                result = db.execute("INSERT INTO portfolio (user_id, stock, symbol, price, numshares, valuestocks, date, time, buyorsell) VALUES(:user_id, :stock, :symbol, :price, :numshares, :valuestocks, :date, :time, :buyorsell)", user_id = session["user_id"], stock = stockname, symbol = stocksymbol, price = stockprice, numshares = shares, valuestocks = totalvalue, date = d, time = t, buyorsell = 'BUY')
 
                if result != None:
                    db.execute("UPDATE users SET cash = :cash WHERE id = :user_id", cash = user_cash[0]['cash'] - totalvalue, user_id = session["user_id"])

                    # Redirect user to index
                    flash('BUY SUCCESSFUL')
                    return redirect("/")

# User reached route via GET (as by clicking a link or via redirect)
else:
    return render_template("buy.html")

Looking at the log file, there is a problem with the application trying to multiply two variables, one of which is of type 'NonType' and the other is an int. Since there is only one line of code where I multiply two values, it should result from:

totalvalue = (stockprice * shares)

But given all the other earlier IF conditions I cannot see how either stockprice or shares can have the value None and so is of type NonType.

Here's my code for the index application:

def index():
    """Show portfolio of stocks"""
# User reached page via redirect
if request.method == "GET":

    # Lookup username and cash of current user and store in variables
    user = db.execute("SELECT username FROM users WHERE id = :user_id", user_id = session["user_id"])
    cash = db.execute("SELECT cash FROM users WHERE id = :user_id", user_id = session["user_id"])

    # Lookup current portfolio of user and store in variable sumshares
    sumshares = db.execute("SELECT stock, symbol, SUM(numshares), price, valuestocks FROM portfolio WHERE user_id = :user_id GROUP BY stock", user_id = session["user_id"])
 
    # Define variable for total value of all stocks and initialize to zero
    totalvaluestocks = 0

    # Update sumshares with latest stock prices
    for i in range(len(sumshares)):
        sumshares[i]['price'] = lookupindex(sumshares[i]['symbol'])
        sumshares[i]['valuestocks'] = sumshares[i]['price'] * sumshares[i]['SUM(numshares)']
        totalvaluestocks = totalvaluestocks + sumshares[i]['valuestocks']

        # Update to format USD
        sumshares[i]['price'] = usd(sumshares[i]['price'])
        sumshares[i]['valuestocks'] = usd(sumshares[i]['valuestocks'])

    # Calculate grand total
    grandtotal = cash[0]['cash'] + totalvaluestocks

    # format values to USD
    grandtotal = usd(grandtotal)
    cash[0]['cash'] = usd(cash[0]['cash'])
    totalvaluestocks = usd(totalvaluestocks)

    # Generate index page
    return render_template("index.html", user = user[0]['username'], cash = cash[0]['cash'], totalvaluestocks = totalvaluestocks, sumshares = sumshares, grandtotal = grandtotal)

# User reached route via POST (as by submitting a form via POST)
elif request.method == "POST":

    # Check for valid input
    try:
        extracash = float(request.form.get("extracash"))

    except ValueError:
        return apology("Please type in valid cash amount", 403)
 
    # Add cash to user
    current = db.execute("SELECT cash FROM users WHERE id = :user_id", user_id = session["user_id"])
    db.execute("UPDATE users SET cash = :cash WHERE id = :user_id", cash = current[0]['cash'] + extracash, user_id = session["user_id"])

    # Return user to home page
    return redirect("/")

Looking at the log file, there is a problem with the application trying to multiply two variables, one of which is of type 'NonType' and the other is an int. Since there is only one line of code in my whole program where I multiply two values, one of them being an int it should result from:

sumshares[i]['valuestocks'] = sumshares[i]['price'] * sumshares[i]['SUM(numshares)']

This line of code is meant to update the value of the stock with the current price info. So instead of showing the historic price (at time of purchase), it shows the current price.

In the buy section there is another multiplication, but that multiplication has no ints as input.

Source Link
JJuice
  • 119
  • 5

Pset 7 - check50 error on buy

Almost finished Pset7 but I'm getting an error on Check50 that I don't understand. The log file says:

:( buy handles valid purchase

Log 
sending POST request to /login 
sending POST request to /buy 
exception raised in application: TypeError: unsupported operand type(s) for *: 'NoneType' and 'int' 

Here's my code for the buy application:

"""Buy shares of stock"""

# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":

    # Ensure stock symbol was submitted
    if not request.form.get("symbol"):
        return apology("Missing stock's symbol", 400)

    else:
        # Ensure float number of shares was submitted
        try:
            shares = float(request.form.get("shares"))

        except ValueError:
            return apology("Please submit number of shares", 400)

        # Ensure positive integer number of shares was submitted
        if (shares % 1) != 0 or (shares < 0):
            return apology("Please submit number of shares", 400)

        # Check if stock exists
        elif (lookup(request.form.get("symbol")) == None):
            return apology("Stock does not exist", 400)

        else:
            # Check stock and store info in variables
            stock = lookup(request.form.get("symbol"))
            stockname = stock['name']
            stockprice = stock['price']
            stocksymbol = stock['symbol']
            totalvalue = (stockprice * shares)

            # Calculate current date and time
            now = datetime.now()
            d = now.date()
            t = now.time()

            # Lookup user's available cash and store in variable
            user_cash = db.execute("SELECT cash FROM users WHERE id = :user_id", user_id = session["user_id"])

            # Ensure user has enough cash
            if totalvalue > user_cash[0]['cash']:
                return apology("Not enough cash to buy", 403)

            else:
                # add transaction to the portfolio table
                result = db.execute("INSERT INTO portfolio (user_id, stock, symbol, price, numshares, valuestocks, date, time, buyorsell) VALUES(:user_id, :stock, :symbol, :price, :numshares, :valuestocks, :date, :time, :buyorsell)", user_id = session["user_id"], stock = stockname, symbol = stocksymbol, price = stockprice, numshares = shares, valuestocks = totalvalue, date = d, time = t, buyorsell = 'BUY')

                if result != None:
                    db.execute("UPDATE users SET cash = :cash WHERE id = :user_id", cash = user_cash[0]['cash'] - totalvalue, user_id = session["user_id"])

                    # Redirect user to index
                    flash('BUY SUCCESSFUL')
                    return redirect("/")

# User reached route via GET (as by clicking a link or via redirect)
else:
    return render_template("buy.html")

Looking at the log file, there is a problem with the application trying to multiply two variables, one of which is of type 'NonType' and the other is an int. Since there is only one line of code where I multiply two values, it should result from:

totalvalue = (stockprice * shares)

But given all the other earlier IF conditions I cannot see how either stockprice or shares can have the value None and so is of type NonType.

Also the buy operation works as expected, when I type in an existing stock, a valid number of shares and have enough cash. Can someone help me out with a suggestion or knows where this error might be coming from?