Open varunm532 opened 2 months ago
For my project I use three tables: Stocks table, Stock_transaction table, and a shared users table:
_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```
![image](https://github.com/varunm532/varun2/assets/142542401/8b1b1ab1-2aea-4103-92ea-1d17b11a478e)
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.
data extracted from stocks table ( a table contain info about stocks)
(data in form of dictanory from 3rd party api to update prices)
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.
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):
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.
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
In the Chrome browser, show a demo (GET) of obtaining an Array of JSON objects that are formatted into the browsers screen.
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);
});})
}
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
(This code handles a successful response. 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.)
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.');
(this code handels the errors. 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)
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.
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);
});})
}
Show algorithms and preparation of data for analysis. This includes cleaning, encoding, and one-hot encoding.
(cleaned data necessary for predicting and it one-hot encoding wasn't necessary for this.)
Show algorithms and preparation for predictions.
cleaned csv data and set up regression model
cleaned json data from frontend used to predict
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.
Collections
Blog Python Model code and SQLite Database.
From VSCode using SQLite3 Editor, show your unique collection/table in database, display rows and columns in the table of the SQLite database.
From VSCode model, show your unique code that was created to initialize table and create test data.
Lists and Dictionaries
Blog Python API code and use of List and Dictionaries.
In VSCode using Debugger, show a list as extracted from database as Python objects.
In VSCode use Debugger and list, show two distinct example examples of dictionaries, show Keys/Values using debugger.
APIs and JSON
Blog Python API code and use of Postman to request and respond with 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.
In VSCode, show algorithmic conditions used to validate data on a POST condition.
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.
In Postman, show the JSON response for error for 400 when missing body on a POST request.
In Postman, show the JSON response for error for 404 when providing an unknown user ID to a UPDATE request.
Frontend
Blog JavaScript API fetch code and formatting code to display JSON.
In Chrome inspect, show response of JSON objects from fetch of GET, POST, and UPDATE methods.
In the Chrome browser, show a demo (GET) of obtaining an Array of JSON objects that are formatted into the browsers screen.
In the Chrome browser, show a demo (POST or UPDATE) gathering and sending input and receiving a response that show update. Repeat this demo showing both success and failure.
Optional/Extra, Algorithm Analysis
In the ML projects, there is a great deal of algorithm analysis. Think about preparing data and predictions.
Show algorithms and preparation of data for analysis. This includes cleaning, encoding, and one-hot encoding.
Show algorithms and preparation for predictions.
Discuss concepts and understanding of Linear Regression algorithms.
Discuss concepts and understanding of Decision Tree analysis algorithms.