varunm532 / varun2

MIT License
0 stars 0 forks source link

Varun Manoj PIllai | Data Structure Writeup #22

Open varunm532 opened 2 months ago

varunm532 commented 2 months ago

Collections

Blog Python Model code and SQLite Database.

Lists and Dictionaries

Blog Python API code and use of List and Dictionaries.

APIs and JSON

Blog Python API code and use of Postman to request and respond with JSON.

Frontend

Blog JavaScript API fetch code and formatting code to display JSON.

varunm532 commented 2 months ago

Collections:

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

varunm532 commented 2 months ago

Lists and Dictionaries

blog: for my api code that update the price of stocks, it uses a third-party api which returns data about a specific stock in the form of a dictionary. For my project, I don't require this much info therefore, from the dictionary, the only data I take is the price. Furthermore, for another api-endpoint I create a list from my stock-transaction table. This list contains all the data for each transaction done by the user. With this list, I use a for loop to find how many stocks the person owns and the price of all the stocks the user owns.

image data extracted from stocks table ( a table contain info about stocks)

image image image (data in form of dictanory from 3rd party api to update prices)

varunm532 commented 2 months ago

APIs and JSON

blog: One of my post endpoint api code is for selling stock. This code first takes data from the frontend through json ( uid, stock symbol, quantity of stocks). Then from the stock_transaction table,it filters for all transitions for the specific user and stock symbol and uses this to find the total number of stocks the user owns for the specific stock. Then it checks if the user is trying to sell more stocks than he/she own. If it passes the check, it first takes the price of the stock from the stocks table. Then with calculates the total price of the transaction. With that it creates a log in the transaction table. The it filters for the quantity of the specific stock and saves it in a variable and adds that with the quantity of stocks sold to update the total quantity of stocks in the stocks table. Then from the users tables, it filters of stockmoney from the uid and adds the current amount to price gained from selling. After that calculation, it updates stockmoney.

The code below will receive a request from the front end mainly User ID, Stock Symbol and Quantity. This data is directed to the POST method and perform database operation. The code snippet is from Flask application. The HTTP POST request is processed by the code and update the database table. After the database operation, the code will return appropriate response to the client based on the outcome of the operation.

image

 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

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.

currentprice = list1[0]['sheesh'] transactionamount = currentprice * quantity

After the successful sale transaction, the user's available money is updated. The code retrieves the user's current money (currentmoney) and calculates the new amount after the transaction (newmoney). This ensures that the user's money is updated correctly.

currentmoney = list2[0]['stockmoney'] newmoney = currentmoney + transactionamount

Once the sell transaction is completed, the quantity of the stock in the database is updated. The code retrieves the current quantity (tableid) and calculates the new quantity after the transaction (newquantity). This ensures that the stock quantity is updated accurately.

tableid = list1[0]['quantity'] newquantity = tableid + quantity

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.

image

image

varunm532 commented 2 months ago

Frontend

Blog: My Api fetch code contain jsonified "payload" required for the api to work. In my buy fetch code, if there is no error, then the code will console log "success" and then it refreshes the get function to update the table of stock. Then it will run the get function to display the account balance. 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 and the second else handels an invalid input

image

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.

varunm532 commented 2 months ago

Optional/Extra, Algorithm Analysis

image cleaned csv data and set up regression model image cleaned json data from frontend used to predict

jplip commented 2 months ago

You were very thorough with what the project is. I think that finance is very important and the amount of detail you put into the comments for the images is nice. The code and the number of databases used are amazing. You used 3 unique tables and that is something that I can learn from. I always put everything in one table so this was something to learn. One small critique is that when we were talking about the trimester 3 project, we got to talking about how yours was about food and finance. I think that styling could definitely be added to make the whole site pop for the ML. Food is meant to be in your face with lively and vibrant color. I think that just adding some styling would be nice instead of the default look. This however is very easy to solve and from the looks of it, you have majority if not all the code working perfectly. I think this is a very good project and a very well put together writeup to follow.