Still working on index in pset 7. I am able to display details of the shares held by the user and their cash balance in a table. I have done this by iterating over their holdings in a portfolio table, calling lookup on each symbol and appending the details of lookup to the line. However I cant figure out how to add the value of all the users shareholdings to get a total value for shares held so that this can then be added to their cash balance to get their total equity (i.e. shares + cash). I think maybe the SQL SUM statement should be used but I cant see how to do this as the total current value of the shares are not in table (as mentioned above, they are being appended to the list. I have set out my code below. Any help would be greatly appreciated.

def index():

#Get holdings of the user
holdings = db.execute("SELECT symbol, shares, price FROM portfolio WHERE id = :id", id = session['user_id'])

for line in holdings: 
    symbol = str(line["symbol"])
    quote = lookup(symbol)
    line["name"] = (quote['name'])
    line["current_price"] = usd(quote['price'])
    line["value_shares"] = usd(line["shares"] * quote['price'])

#get remaining cash for user 
cash = db.execute("SELECT cash FROM users WHERE id = :id", id = session['user_id'])

quote_cash = usd(cash[0]["cash"])

return render_template("index.html", holdings = holdings, quote_cash = quote_cash)

1 Answer 1


You could add an accumulator in the for line loop (like tot_val += line["value_shares"], and then make quote_cash a list where quote_cash[0] is the cash and quote_cash[1] is shares value.

  • Thanks for your help. Do I need to do something with the line["value_shares] so that they can be added together? I have tried the above but get error that + is not allowed operand for str. I tried casting it to a float but then get message saying this cant be done on the str.
    – Breninio
    Commented Mar 28, 2017 at 19:02
  • 1
    maybe do the calc like tot_val += line['shares'] * quote['price'] so it's using numerics? Commented Mar 28, 2017 at 21:53
  • That worked. Thanks a million for the help DinoCoderSaurus. Moving on to Sell now! Hopefully it doesnt take me as long as index!
    – Breninio
    Commented Mar 29, 2017 at 18:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .