Collections:

From VSCode using SQLite3 Editor, show your unique collection/table in database, display rows and columns in the table of the SQLite database:

  • For my project I use three tables: Stocks table, Stock_transaction table, and a shared users table:
    • image

      • This is my stocks table and in this table I store :
        • top 25 stocks with respective data about stocks’ symbol, company name, market cap and current price (sheesh)
        • I use a third party api to update the price of each stock in real time
    • image
      • This is my stock_transactions table and in this table I store:
        • the current user, the stock bought, action(buy/sell), quantity, value of transaction
        • this table is used to log user transactions and used to calculate account balance
    • image
      • This is my shared users table:
        • In this table, I store user specific data, like the account balance

From VSCode model, show your unique code that was created to initialize table and create test data:

  • This is my initialization code for my stocks table:
    • image
    • class Stocks(db.Model):
        _tablename_ = 'stocks'
                
        # define the stock schema with "vars" from object
        id = db.Column(db.Integer, primary_key=True)
        _symbol = db.Column(db.String(255),unique=False,nullable=False)
        _company = db.Column(db.String(255),unique=False,nullable=False)
        _quantity = db.Column(db.Integer,unique=False,nullable=False)
        _sheesh = db.Column(db.Integer,unique=False,nullable=False)
                
        # constructor of a User object, initializes the instance variables within object (self)
        def __init__(self,symbol,company,quantity,sheesh):
            self._symbol = symbol
            self._company = company
            self._quantity = quantity
            self._sheesh = sheesh
      
    • This code defines the different colums of my stocks table and defines the data parameters for each column
    • The above picture contain all the crud operations for the stocks table
  • This is my initialization code for my stock_transactions table:
    • image

    •   class Stock_Transactions(db.Model):
          __tablename__ = 'stock_transactions'
      
          # define the stock schema with "vars" from object
          id = db.Column(db.Integer, primary_key=True)
          _uid = db.Column(db.String(255), unique=False, nullable=False)
          _symbol = db.Column(db.String(255),unique=False,nullable=False)
          _transaction_type = db.Column(db.String(255),unique=False,nullable=False)
          _quantity = db.Column(db.String(255),unique=False,nullable=False)
          _transaction_amount = db.Column(db.Integer, nullable=False)
          # constructor of a User object, initializes the instance variables within object (self)
      
          def __init__(self,uid,symbol,transaction_type,quantity,transaction_amount):
              self._uid = uid
              self._symbol = symbol
              self._transaction_type = transaction_type
              self._quantity = quantity
              self._transaction_amount = transaction_amount
      
    • This code defines the different colums of my stock_transction table and defines the data parameters for each column -This picture above contains the code of all the crud operations for my stock_transaction code
  • This code creates “test-data” aka for my project, it populates my stock table data from top 25 stocks from a csv file:
    • image

Lists and Dictionaries

In VSCode using Debugger, show a list as extracted from database as Python objects.

  • image
    • In this list, each element is actually a row of data from the stock_transaction table.
    • Each element is a transaction and this list is used for a for loop that returns all the stocks the user owns and its current price

In VSCode use Debugger and list, show two distinct example examples of dictionaries, show Keys/Values using debugger.

  • image
    • This is a dictionary that contains data returned form a 3rd party api used to update price of each stock in stocks table
  • image
    • This is json dictionary returned from the frontend and the key/values are used for a buy feature

APIs and JSON

In VSCode, show Python API code definition for request and response using GET, POST, UPDATE methods. Discuss algorithmic condition used to direct request to appropriate Python method based on request method.:

  • Post method:

    class _SellStock(Resource):
            def post(self):
                # getting key variables from frontend
                body = request.get_json()
                symbol = body.get('symbol')
                uid = body.get('uid')
                quantity = body.get('quantity')
                #other variables:
                transactiontype = 'sell'
                #SQL taking data from transation table
                result = db.session.query(
                    Stock_Transactions._symbol.label("SYMBOL"),
                    (func.sum(case([(Stock_Transactions._transaction_type == 'buy', Stock_Transactions._quantity)], else_=0)) -
                    func.sum(case([(Stock_Transactions._transaction_type == 'sell', Stock_Transactions._quantity)], else_=0))
                    ).label("TOTAL_QNTY"),
                    (func.sum(Stock_Transactions._quantity * Stocks._sheesh)).label("VALUE"),
                ).join(Stocks, Stocks._symbol == Stock_Transactions._symbol) \
                .filter(Stock_Transactions._uid == uid, Stock_Transactions._symbol == symbol) \
                .group_by(Stock_Transactions._symbol) \
                .all()
                print(result[0][1])
                ownedstock = result[0][1]
                print(ownedstock)
                #logic for selling stock
                if (ownedstock >= quantity):
                    #logic for transaction log
                    sellquantity = -quantity
                    stocks = Stocks.query.all()
                    json_ready = [stock.read() for stock in stocks]
                    list1 = [item for item in json_ready if item.get('symbol') == symbol]
                    currentprice = list1[0]['sheesh']
                    transactionamount = currentprice*quantity
                    Inst_table = Stock_Transactions(uid=uid, symbol=symbol,transaction_type=transactiontype, quantity=quantity, transaction_amount=transactionamount)
                    print(Inst_table)
                    Inst_table.create()   
                    db.session.commit()
                    #logic for updating money in user table
                    users = User.query.all()
                    json_ready = [user.read() for user in users]
                    list2 = [item for item in json_ready if item.get('uid') == uid]
                    currentmoney = list2[0]['stockmoney']
                    newmoney = currentmoney + transactionamount
                    user_ids = User.query.filter(User._uid == uid).value(User.id)
                    tableid_user = User.query.get(user_ids)
                    print(tableid_user)
                    tableid_user.stockmoney = newmoney
                    db.session.commit()
                    ### update quantity in stock table
                    tableid = list1[0]['quantity']
                    print(tableid)
                    newquantity = tableid + quantity
                    tableid = list1[0]['id']
                    tableid = Stocks.query.get(tableid)
                    tableid.update(quantity=newquantity )
                    db.session.commit()
                    # Call the _Graph class to generate and save the graph
                    return {'message': 'Stock sold successfully'}, 200
                else:
                    return {'message': 'Insufficient stock quantity to sell'}, 400
    
    • this code returns an error if the user tries to sell more stocks that owned
    • This code uses CRUD operations to:
      • first read the stock_transaction table to check if the user has enough stocks to sell and validates it with an if/else
      • reads the stocks table to get the current price of stock
      • creates a new row of data in the stock_transactions table to log transaction
      • updates the account balance in the users table
      • updates the quantity of the specific stock in the stocks table

In VSCode, show algorithmic conditions used to validate data on a POST condition.

  • The code also validate the quantity of stock owned by the transaction user:
    if (ownedstock >= quantity):
        # Logic for selling stock
    else:
        return {'message': 'Insufficient stock quantity to sell'}, 400
    
    • Before executing the sell transaction, the code calculates the transaction amount based on the current price of the stock (currentprice) and the quantity to be sold (quantity). This ensures that the transaction amount is accurately computed.
    • These algorithmic conditions ensure that the data received in the POST request is validated and processed correctly to perform the sell transaction and update the database accordingly.

In Postman, show the JSON response for error for 400 when missing body on a POST request.

  • image

In Postman, show URL request and Body requirements for GET, POST, and UPDATE methods./In Postman, show the JSON response data for 200 success conditions on GET, POST, and UPDATE methods.

  • image
  • image

Frontend

In Chrome inspect, show response of JSON objects from fetch of GET, POST, and UPDATE methods.

  • image

In the Chrome browser, show a demo (GET) of obtaining an Array of JSON objects that are formatted into the browsers screen.

  • image
    • In JavaScript code, show code that performs iteration and formatting of data into HTML.
  • Document.addEventListener("DOMContentLoaded", function () {
                  // Function to make API call and update the table
                  function fetchData() {
                      fetch('http://127.0.0.1:8008/api/stocks/stock/display')
                          .then(response => response.json())
                          .then(data => {
                              updateTable(data);
                          })
                          .catch(error => console.error('Error fetching data:', error));
                  }
                  // Function to update the table with data
                  function updateTable(data) {
                      const tableBody = document.querySelector('#stockTable tbody');
                      tableBody.innerHTML = ''; // Clear existing rows
                      data.forEach(stock => {
                          const row = document.createElement('tr');
                          row.innerHTML = `
                              <td>${stock.symbol}</td>
                              <td>${stock.company}</td>
                              <td>${stock.quantity}</td>
                              <td>${stock.sheesh}</td>
                              <td><button class="buy-button" onclick="buyStock('${stock.sym}')">Buy</button></td>
                              <td><button class="sell-button" onclick="sellStock('${stock.sym}')">Sell</button></td>
                          `;
                          tableBody.appendChild(row);
                          const sellButton = row.querySelector('.sell-button')
                          sellButton.addEventListener('click', function(){
                              sellStock(stock.symbol,stock.quantity);
                          })
                          const buyButton = row.querySelector('.buy-button');
                          buyButton.addEventListener('click', function () {
                              buyStock(stock.symbol,stock.quantity);
                      });})
                  }
      })
    
  • This code first gets an Array of JSON object from the backend about the data in the stocks table
  • Then through itteration and DOM:
    • it creates a new table row element
    • adds the data in JSON object in differnt table datas
    • and finaly appends the row so the the table in the picture above is dynamically created

In JavaScript code, show and describe code that handles success. Describe how code shows success to the user in the Chrome Browser screen.

  •   fetch(url, authOptions)
                              .then(response => {
                                  if (!response.ok) {
                                      throw new Error(`HTTP error! Status: ${response.status}`);
                                  }
                                  return response.json();
                              })
                              .then(data => {
                                  console.log( "success": data);
                                  fetchData();  // Refresh the data after a successful buy
                                  Balance();    // Update balance after a successful buy
    
  • If there is no error, then the code will console log “success”
  • then it refreshes the get function to update the table of stock.
  • Then it will run the get function to display the account balance.

In JavaScript code, show and describe code that handles failure. Describe how the code shows failure to the user in the Chrome Browser screen.

  •   .catch(error => {
                                  console.error('error', error);
                                  alert('Insufficient Balance')
                              });
                      } else {
                          alert('Invalid quantity. The requested quantity exceeds the available quantity.');
                      }
                  } else {
                      alert('Buy operation canceled or invalid quantity entered.');
    
  • If the post request fails, it alert the user that the user doesn’t have enough money.
  • For the else commands, the first else handles error with the user tries to buy more stocks that publically available
  • the second else handels an invalid input

In JavaScript code, describe fetch and method that obtained the Array of JSON objects.

The fetch function takes two parameters, url: The URL to which the request is made. authOptions: Authentication options, such as headers or credentials, that are included in the request. .then(): This method is used to handle the response from the server. Error handling is done in this line: if (!response.ok) { throw new Error(HTTP error! Status: ${response.status}); }

the response.json() method is used to parse the JSON data returned by the server. The .then() method is employed to handle both successful responses and errors, with appropriate error handling and data processing.

In JavaScript code, show code that performs iteration and formatting of data into HTML.

document.addEventListener("DOMContentLoaded", function () {
                // Function to make API call and update the table
                function fetchData() {
                    // Replace 'your-api-endpoint' with the actual API endpoint
                    fetch('http://127.0.0.1:8008/api/stocks/stock/display')
                        .then(response => response.json())
                        .then(data => {
                            updateTable(data);
                        })
                        .catch(error => console.error('Error fetching data:', error));
                }
                // Function to update the table with data
                function updateTable(data) {
                    const tableBody = document.querySelector('#stockTable tbody');
                    tableBody.innerHTML = ''; // Clear existing rows
                    data.forEach(stock => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${stock.symbol}</td>
                            <td>${stock.company}</td>
                            <td>${stock.quantity}</td>
                            <td>${stock.sheesh}</td>
                            <td><button class="buy-button" onclick="buyStock('${stock.sym}')">Buy</button></td>
                            <td><button class="sell-button" onclick="sellStock('${stock.sym}')">Sell</button></td>
                        `;
                        tableBody.appendChild(row);
                        const sellButton = row.querySelector('.sell-button')
                        sellButton.addEventListener('click', function(){
                            sellStock(stock.symbol,stock.quantity);
                        })
                        const buyButton = row.querySelector('.buy-button');
                        buyButton.addEventListener('click', function () {
                            buyStock(stock.symbol,stock.quantity);
                    });})
                }
  • This code first gets an Array of JSON object from the backend about the data in the stocks table
    • Then through itteration and DOM:
      • it creates a new table row element
      • adds the data in JSON object in differnt table datas
      • and finaly appends the row so the the table in the picture above is dynamically created

Optional/Extra, Algorithm Analysis

Show algorithms and preparation of data for analysis. This includes cleaning, encoding, and one-hot encoding.

image

  • This code cleanes the csv file data:
    • The DayPart colum is cleaned so that its values are in 1’s (Morning) and 0’s (Afternoon)
    • The DayType cloumn is cleaned as that its values are in 1’s (weekend) and 0’s (weekday)
    • The time column is cleaned so that from the time format saved in the csv file, the only thing being considerd is hours

Show algorithms and preparation for predictions.

  • image
    • This code cleans the csv data
    • fits the target ( item wanting to be predicted) as y-value in both logistic regression and dession tree and features (itsem used to predict) as x-value in both logistic regression and dession tree
  • image
    • This code cleans the json input:
      • The DayPart colum is cleaned so that its values are in 1’s (Morning) and 0’s (Afternoon)
      • The DayType cloumn is cleaned as that its values are in 1’s (weekend) and 0’s (weekday)
      • The time column is cleaned so that from the time format saved in the csv file, the only thing being considerd is hours