{% extends "layout.html" %}

{% block title %}
{% endblock title %}

{% block main %}

    <th> SYMBOL </th>
    <th> NAME </th>
    <th> SHARES </th>
    <th> PRICE </th>
    <th> TOTAL </th>

<!-- if db_shares > 1 because have at least 1 stock at this point -->
{% if length_db_shares >  1 %}

<!-- call rows -->

  {% for i in db_stock_info %}

    <th> {{db_stock_info[i]["stock_symbol"]}} </th>
    <th> {{db_stock_info[i]["stock_name"]}}  </th>
    <th> {{db_stock_info[i]["shares"]}}    </th>
    <th> {{db_stock_info[i]["stock_price"]}} </th>
    <th> {{db_stock_info[i]["stock_total"]}} </th>
    {% endfor %}

{% endif %}

      <th> </th>
      <th> </th>
      <th> </th>
      <th> </th>
      <th> {{ cash_after_purchase}} </th>
        <th> </th>
        <th> </th>
        <th> </th>
        <th> </th>
        <th> {{ total_cash}} </th>


{% endblock %}


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

    # need to go here so can take both routes!

    # get current symbol from global variable
    current_symbol = session["user_symbol"]
    print("current_symbol {}", current_symbol)
    current_id = session["user_id_2"]

    # get cash_before_purchase
    db_total_cash = db.execute('SELECT total_cash FROM users WHERE id = :present_id',
    present_id = current_id)

    # get cash after purchase
    db_cash_after_purchase = db.execute("SELECT cash_after_purchase FROM users WHERE id = :present_id",
    present_id = current_id)

    db_shares = db.execute("SELECT shares FROM stock_info WHERE stock_symbol = :not_db_symbol AND id = :present_id",
    not_db_symbol = current_symbol, present_id = current_id)

    # only execute from buy route
    if len(db_shares) != 0:

        #id_db= db.execute("SELECT COL_LENGTH ( 'users' , 'id' ) WHERE id = :present_id",
        #present_id = current_id)

        # select everything but id
        db_stock_info = db.execute("SELECT stock_symbol, stock_name, shares, stock_price, stock_total FROM stock_info WHERE id = :present_id",
        present_id = current_id)

        # stock_price * shares
        db_stock_total = db.execute("SELECT stock_total FROM stock_info WHERE id = :present_id AND stock_symbol = :present_symbol"
        ,present_id = current_id, present_symbol = current_symbol )

        # pass on to sell.html
        db_stock_symbol = db.execute("SELECT stock_symbol FROM stock_info WHERE id = :present_id",
        present_id = current_id)

        length_db_stock_symbol = len(db_stock_symbol)

        # display id
        # displays stock_info = symbol, name, shares, price, total (can be more than 1 stock)
        # displays  total_cash iow cash_after_purchase
        # displays  stock_total + cash_after_purchase
        i = 0
        return render_template("index.html",
        length_db_shares = len(db_shares),
        db_stock_info = db_stock_info,
        total_cash = db_total_cash[0]["total_cash"],
        cash_after_purchase = db_cash_after_purchase[0]["cash_after_purchase"] )

    # not buy route
        return render_template("index.html",
        length_db_shares = len(db_shares),
        total_cash = db_total_cash[0]["total_cash"],
        cash_after_purchase = db_cash_after_purchase[0]["cash_after_purchase"])


@app.route("/buy", methods=["GET", "POST"])
def buy():
    """Buy shares of stock"""

    if request.method == "POST":

        symbol = request.form.get("symbol")
        print (symbol)
        # Remove Space at the Start and end of the string in Python  :
        upper_case_symbol = symbol.upper()
        # http://www.datasciencemadesimple.com/remove-spaces-in-python/
        symbol = upper_case_symbol.strip()
        # why moving this up makes it work moving the codes down make it not work?

        """check for errors"""

        if not symbol or symbol == None:
            return apology("Stock symbol is inputted incorrect or blank.", 403)

        # confused by not
        if not request.form.get("counter"):
            return apology("you didn't click shares")

        """ use lookup function"""
        stocks = lookup(symbol)
        user_price =  stocks["price"]
        user_symbol = stocks["symbol"]
        user_fullname = stocks["name"]

        not_db_shares = request.form.get("counter")

        current_id = session["user_id"]

        """ put this here because want to count shares before insert
         may come back empty as in 0 that works"""
        db_shares = db.execute("SELECT shares FROM stock_info WHERE stock_symbol = :not_db_symbol and id = :present_id",
        not_db_symbol = symbol, present_id = current_id)

        db_stock_price = db.execute("SELECT stock_price FROM stock_info WHERE id = :user_id AND stock_symbol = :not_db_symbol",
        user_id  = current_id, not_db_symbol = symbol)

        """ already have at least one share also calculate new_total_stock_price and new total shares"""
        # https://stackoverflow.com/questions/3289601/null-object-in-python
        if len(db_shares) > 0:

            # stock_total                        193.34           1                                   193.34                    1
            stock_total = (user_price * int(not_db_shares)) + (db_stock_price[0]["stock_price"] * db_shares[0]["shares"])

            not_db_shares = db_shares[0]["shares"] + int(not_db_shares)

            # update shares # why can't go in if statement above
            db.execute("UPDATE stock_info SET shares = :present_shares WHERE id = :present_id AND stock_symbol = :not_db_symbol",
            present_id = current_id, present_shares = not_db_shares, not_db_symbol = symbol)
            """calculate new_total_stock_price if have 0 shares"""
            stock_total = user_price * int(not_db_shares)

        db_total_cash = db.execute('SELECT total_cash FROM users WHERE id = :present_id',
        present_id = current_id)

        """can the user afford the stock"""
        # another error checker
        if db_total_cash[0]["total_cash"] < stock_total:
            return apology("You don't have enough money.",403)
         # update stock_total
        db.execute("UPDATE stock_info SET stock_total = :present_stock_total WHERE id = :present_id AND stock_symbol = :not_db_symbol",
        present_id = current_id, present_stock_total = stock_total, not_db_symbol = symbol)

        """calculate cash_after purchase"""
        cash_after_purchase = db_total_cash[0]["total_cash"] - stock_total

        db.execute("UPDATE users SET cash_after_purchase = :update_cash_after_purchase WHERE id = :present_id",
        present_id = current_id, update_cash_after_purchase = cash_after_purchase)

        """add all information in stock_info this is when adding brand new info into a database but may have same id"""

        if len(db_shares) == 0:

            db_symbol = db.execute("INSERT INTO stock_info (id,stock_name, stock_symbol, shares, stock_price, stock_total)\
            VALUES(:present_id, :name_stock, :user_symbol, :total_shares, :single_stock_price, :total_price)",
            present_id = current_id,
            name_stock = user_fullname,
            user_symbol = symbol,
            total_shares = not_db_shares,
            single_stock_price = user_price,
            total_price = stock_total)

        """ pass on stock_symbol to index using global variable """
        db_symbol = db.execute("select stock_symbol from stock_info where id = :present_id",
        present_id = current_id)

        # global variable
        session["user_symbol"] = db_symbol[0]["stock_symbol"]
        session["user_id_2"] = current_id
        return redirect ("/")

        return render_template("buy.html")

<tr{{[i]}}> looks plain wrong to me. I don't think there should be anything within that tr opening tag, and I could imagine it not showing up even for that one.

{% for i in db_stock_info %} has i take the values of the individual db_stock_info elements, a single row (represented by a dict). It is not an index. loop.index or loop.index0 could be used as an index, but there's little need for.

I don't think you should show the portfolio with buy-time prices, maybe they are interesting, but more so is the current portfolio value. I think you should call lookup for any symbol owned to determine the current price, and show that in addition or instead.

I don't understand the "user_symbol". What is that meant to describe? And what if it doesn't exist after logging in?

You need to follow the specification. It states the buy form needs to use input names symbol and shares, not symbol and counter. And it might be worth testing symbol for None before you upper().

You don't seem to record the user actions for the history page.

Your variable names and code might need a bit rework, I find it hard to understand. The variable user_fullname is definitely misleading.

  • imgur.com/a/IiSs1p0 In the imgur file the code is not working in index.html. in application.py row_values = [i.values() for i in db_stock_info] print(row_values) The proper properties print in application.py but they don't work in index.html Eventually I will try incorporating the loop into index.html Any advice? @Blauelf Thanks for the help
    – grggthwrth
    Aug 14 '19 at 0:50

You must log in to answer this question.

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