Skip to content
TheChatArchiveThe Chat Archive
gpt-4-1106-preview· openaiHugging Face Suzhen/CodeChat

I'm trying to implement a stock trading webapp. For some reason my current stocks…

  1. User

    I'm trying to implement a stock trading webapp. For some reason my current stocks overview implementation doesn't work. Please fix it. Here's the flask code: @app.route("/") @login_required def index(): if request.method == "GET": cash = db.execute("SELECT cash FROM users;") symbol = db.execute("SELECT symbol FROM purchases;") price= db.execute("SELECT price FROM purchases;")

        return render_template("index.html")
    return apology("TODO")
    

    And here the html: {% extends "layout.html" %}

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

    {% block main %}

        </thead>
        <tbody>
            {% for purchase in purchases %}
                <tr>
                    <td class="text-start">{{ purchases.symbol }}</td>
                    <td class="text-end">{{ purchases.shares }}</td>
                    <td class="text-end">{{ purchases.price }}</td>
                    <td class="text-end">{{ purchases.total }}</td>
                </tr>
            {% endfor %}
        </tbody>
        <tfoot>
            <tr>
                <td class="border-0 fw-bold text-end" colspan="3">Cash</td>
                <td class="border-0 text-end"></td>
            </tr>
    
            <tr>
                <td class="border-0 fw-bold text-end" colspan="3">TOTAL</td>
                <td class="border-0 w-bold text-end">{{ users.cash }}</td>
            </tr>
        </tfoot>
    
    </table>
    

    {% endblock %}

  2. Assistant

    To help you fix your stock trading webapp, let's make some corrections to your Flask route handler and HTML template.

    Flask Route Handler Corrections:

    The GET method check is redundant since by default Flask treats routes as GET unless specified. Your route does not need to exclusively handle GET requests because it does not process any other methods.

    Secondly, your queries to the database to retrieve cash, symbol, and price appear to be running independently. Presumably, you want to combine these data to show the current state of the user's stock portfolio. You also need to calculate the 'total' for each stock and provide the data to your template context.

    Here's an example of how you can query for the user's current holdings (assumed user_id is stored in session['user_id']):

    @app.route("/")
    @login_required
    def index():
        # Assume db.execute() returns a dict or a list of dicts
        user_cash = db.execute("SELECT cash FROM users WHERE id = :id;", id=session['user_id'])[0]['cash']
        purchases = db.execute("""
            SELECT symbol, SUM(shares) as shares, AVG(price) as price
            FROM purchases WHERE user_id = :id
            GROUP BY symbol
            HAVING SUM(shares) > 0;
            """, id=session['user_id'])
        
        # Calculate totals for each purchase
        for purchase in purchases:
            purchase['total'] = purchase['shares'] * purchase['price']
        
        # Calculate the total value of stocks plus cash
        total_assets = sum(purchase['total'] for purchase in purchases) + user_cash
    
        return render_template("index.html", cash=user_cash, purchases=purchases, total_assets=total_assets)
    

    HTML Template Corrections:

    When iterating over purchases in the template, make sure that you refer to the individual purchase in the loop, not purchases (which is the entire list):

    {% for purchase in purchases %}
        <tr>
            <td class="text-start">{{ purchase.symbol }}</td>
            <td class="text-end">{{ purchase.shares }}</td>
            <td class="text-end">${{ "%.2f"|format(purchase.price) }}</td>
            <td class="text-end">${{ "%.2f"|format(purchase.total) }}</td>
        </tr>
    {% endfor %}
    

    And for the cash and total assets, ensure your variable names match those passed from the route handler:

    <tfoot>
        <tr>
            <td class="border-0 fw-bold text-end" colspan="3">Cash</td>
            <td class="border-0 text-end">${{ "%.2f"|format(cash) }}</td>
        </tr>
        <tr>
            <td class="border-0 fw-bold text-end" colspan="3">TOTAL</td>
            <td class="border-0 fw-bold text-end">${{ "%.2f"|format(total_assets) }}</td>
        </tr>
    </tfoot>
    

    Make sure you have set up your database schema and session variables correctly according to this logic, as mismatches will lead to errors or undesired behavior.