0

application.py

@app.route("/")
@login_required
def index():
    """Show portfolio of stocks"""

    # Select symbol owned by user and its quantity
    purchases = db.execute("SELECT stocks_owned,share_amount FROM Purchase WHERE person_id = ?", session["user_id"])

    # Temporary variable
    total_stock_value = 0

    # Update each symbol prices and total
    for purchase in purchases:
        shares = purchases[0]["share_amount"]
        symbol = purchases[0]["stocks_owned"]
        search = lookup(symbol)
        price =  search["price"]
        total_stock_value =  price * shares

        db.execute("UPDATE Purchase SET price_per_stock = ?, stock_value_asked = ? WHERE person_id = ? AND stocks_owned = ?", price,total_stock_value,session["user_id"],symbol )

    # Query the database for remaining cash
    cash = db.execute("SELECT cash FROM users WHERE id = ?" , session["user_id"])


    purchase_table = db.execute("SELECT * FROM Purchase WHERE person_id = ?", session["user_id"] )
    return render_template("index.html", purchase = purchase_table, remaining_cash = cash)


@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
    """Buy shares of stock"""
    if request.method == "GET":
        return render_template("buy.html")

    if request.method == "POST":
        symbol = request.form.get("symbol")
        search = lookup(symbol)
        price = search["price"]
        shares = int(request.form.get("shares"))

        if not symbol or search == None:
            return apology ("No or Invalid symbol")
        ####
        # Query the database for the current user to make sure the user can afford the current stock
        ####

        # Query the database for available cash
        current_user_row = db.execute("SELECT cash FROM users WHERE id = ?" , session["user_id"])
        current_user_cash = current_user_row[0]["cash"]
        # Value of the stock that the user wants to buy
        stock_value_asked =  price * shares

        # # Cash Balance
        cash_after = current_user_cash - stock_value_asked
        print(f'\n\n{cash_after}\n\n')
        # # Grand Total (Stocks Value + Cash)
        grand_total = stock_value_asked + current_user_cash


        # if user's current cash balance is less then the stock value asked for
        if current_user_cash < stock_value_asked:
            return apology("Insufficient Balance", 403)

        # Select user shares of specified symbol from the database
        user_shares = db.execute("SELECT share_amount FROM Purchase WHERE person_id    = ? AND stocks_owned = ?", session["user_id"], symbol )

        # if user has no shares of the symbol, create new stock
        if not user_shares:
           insert = db.execute("INSERT INTO Purchase (person_id,stocks_owned,share_amount,price_per_stock,remaining_cash,stock_value_asked,grand_total) VALUES(?,?,?,?,?,?,?)",  session["user_id"],symbol,shares,price,cash_after,stock_value_asked,grand_total)

        # if user does, increment the shares count
        else:
            shares_count = user_shares[0]["share_amount"] + shares

            db.execute("UPDATE Purchase SET share_amount = ? WHERE person_id = ?", shares_count, session["user_id"])

        # Update cash in users Table
        db.execute("UPDATE users SET cash = ? WHERE id = ?", cash_after , session["user_id"])

        return redirect("/")


index.html

{% extends "layout.html" %}

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

{% block main %}
    <table class="table table-striped">
        <thead>
            <tr>
                <th> Stocks </th>
                <th> Shares </th>
                <th> Price/Stock </th>
                <th> Total Value </th>
                <th> Cash Balance </th>
                <th> Grand Total </th>
            </tr>
        </thead>

        <tbody>
            {% for i in purchase%}
                <tr>
                    <td> {{ i.stocks_owned }} </td>
                    <td> {{ i.share_amount }} </td>
                    <td> {{ i.price_per_stock }} </td>
                    <td> {{ i.stock_value_asked }} </td>
                    <td> {{ i.remaining_cash }} </td>
                    <td> {{ i.grand_total }} </td>
                </tr>
            {% endfor %}
        </tbody>
    </table>

{% endblock %}
1
  • What view "only shows the balance that was deducted the first time only"?. I would expect users.cash to be correct based on the code. index.html does not display that value. remaining_cash (and grand_total) are "point in time" values since they are created at time of purchase. They would not reflect the current state/value of the customer's portfolio. (Actually, the last stock purchased row should). Aug 1 at 18:15

You must log in to answer this question.

Browse other questions tagged .