<html>
  <link
    rel="stylesheet"
    href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
    crossorigin="anonymous"
  />
  <style>
    .positive:before {
      content: "+";
      color: green;
    }
    .positive {
      color: green;
    }
    .negative {
      color: red;
    }
    th,
    td {
      padding: 1em;
    }
    body {
      margin: 2em auto;
      max-width: 80em;
    }
  </style>
  <body>
    <form action="/buy" method="post">
      <input type="text" placeholder="ticker" name="ticker" />
      <input type="text" placeholder="# shares" name="shares" />
      <input type="text" placeholder="price" name="price" />
      <input type="submit" value="Buy" />
    </form>
    <table id="portfolio">
      <tr>
        <th>Ticker</th>
        <th>Number of shares</th>
        <th>Total cost</th>
        <th>Current value</th>
        <th>Percent change</th>
      </tr>
      <tr>
        <td>Loading...</td>
      </tr>
      <tr></tr>
    </table>
    <a href="/flush">Flush DB</a>
  </body>
</html>
<html>
{
  "AAPL": {
    "total_shares": 15,
    "total_cost": 1550,
    "purchases": [
      {
        "shares": 10,
        "price": 100
      },
      {
        "shares": 5,
        "price": 110
      }
    ]
  },
  "MSFT": {
    "total_shares": 20,
    "total_cost": 4000,
    "purchases": [
      {
        "shares": 20,
        "price": 200
      }
    ]
  }
}
</html>
from replit import db

from flask import Flask, render_template, request, jsonify, url_for, redirect
import json

site = Flask(__name__)

@site.route('/')
def index():
    return render_template('index.html')

site.run(host='0.0.0.0', port=8080)
@site.route('/buy', methods=['POST'])
def buy():
    # Create shares key if it doesn't exist
    if 'shares' not in db.keys():
        db['shares'] = {}

    # Extract values from form
    ticker = request.form['ticker'][:5].upper()
    price = float(request.form['price'])
    shares = int(request.form['shares'])

    if ticker not in db['shares']: # buying these for the first time
        db['shares'][ticker] = { 'total_shares': shares,
                                 'total_cost': shares * price }

        db['shares'][ticker]['purchases'] = [{ 'shares': shares,
                                'price': price }]
    else: # buying more
        db['shares'][ticker]['total_shares'] += shares
        db['shares'][ticker]['total_cost'] += shares * price
        db['shares'][ticker]['purchases'].append({ 'shares': shares,
                                        'price': price})

    return redirect(url_for("index"))