When i sell all the shares i own or even in the case of a new registered user who doesn't own any shares; it doesn't redirect to "/" i.e the main index page but serves me an internal error. It works perfectly everytime even if i have one share in my inventory. Kindly Help! The problem seems to be with the variable currentMoney

def index():
"""Show portfolio of stocks"""

# get the amount of cash with the user
user = db.execute("SELECT cash FROM users WHERE id = :user_id", user_id=session["user_id"])
cashRemaining = user[0]["cash"]

# get info about user's transactions
transaction = db.execute("SELECT symbol, SUM(shares) as total_shares FROM transactions WHERE user_id = :user_id GROUP BY symbol HAVING total_shares > 0", user_id=session["user_id"])

# dictionary to sto re current/latest info about shares
quote = {}

for stock in transaction:
    quote[stock["symbol"]] = lookup(stock["symbol"])

for stock in transaction:
    money = quote[stock["symbol"]]["price"] * stock["total_shares"]
    quote[stock["symbol"]].update({"worthShares": money})

currentMoney = quote[stock["symbol"]]["worthShares"] + cashRemaining

return render_template("index.html", quote=quote, transaction=transaction, currentMoney=currentMoney, cashRemaining=cashRemaining)


currentMoney = quote[stock["symbol"]]["worthShares"] + cashRemaining
UnboundLocalError: local variable 'stock' referenced before assignment
  • i seemed to have found the bug but i am not able to debug!
    – Divij Jain
    Commented May 19, 2020 at 11:50
  • so the variable money; it is assigned as 0 if total shares are 0 corresponding to the user. This is what must be messing up the code. The same problem can also occur if the transaction table is empty i.e the user is new as the traction dictionary would be empty!
    – Divij Jain
    Commented May 19, 2020 at 11:58

1 Answer 1


If transaction is an empty list, as when the execute doesn't return any rows, then stock is never assigned a value.

This line currentMoney = quote[stock["symbol"]]["worthShares"] + cashRemaining gives this error UnboundLocalError: local variable 'stock' referenced before assignment for that reason.

One correction would be to 1) set currentMoney to cashRemaining before the second for loop, and 2) increment it inside that loop.

You must log in to answer this question.

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