Home

Data Structue Plan

Stock Simulator

Introduction

We plan on creating a stock simulator game allows users to practice trading stocks without risking real money. Our simulator will provide a realistic trading experience, featuring real-time stock prices, portfolio management, and performance tracking.

1. Algorithmic Loops

List Comprehension

In our stock simulator, we need to manage lists of stocks, users, and transactions. List comprehension is an efficient way to build these lists.

# List of stock prices
stock_prices = [stock['price'] for stock in stocks if stock['symbol'] in user_portfolio]

Processing Lists

We will demonstrate two methods of processing a list: conventional loops and the for each method.

Conventional Loop

# Calculate total portfolio value
total_value = 0
for stock in user_portfolio:
    total_value += stock['quantity'] * stock['price']

For Each Method

# Calculate total portfolio value using sum() and a generator expression
total_value = sum(stock['quantity'] * stock['price'] for stock in user_portfolio)

2. Sorting and Searching

Sorting

Sorting is important for displaying stocks in an organized way. We’ll use SQLite for database queries, which allows efficient sorting.

# Query to sort stocks by price
sorted_stocks = session.query(Stock).order_by(Stock.price.desc()).all()

Searching

Searching for stocks or transactions is another common operation. We can us SQLites filtering capabilities.

# Query to find a specific stock by symbol
stock = session.query(Stock).filter_by(symbol='AAPL').first()

3. Big(O) Notation

Understanding the time and space complexity of our algorithms is vital for ensuring the scalability of our application.

Time Complexity

Space Complexity

4. 2D Iteration

In some cases, we need to process data in a diff format. For example, generating a report of user transactions.

# 2D iteration over a bunch of transactions
transactions = [
    {'user': 'tanay', 'stock': 'AAPL', 'quantity': 10},
    {'user': 'inaad', 'stock': 'GOOGL', 'quantity': 5},
]

for transaction in transactions:
    for key, value in transaction.items():
        print(f"{key}: {value}")

5. Deployment

Full Stack Deployment

Deploying our stock simulator involves setting up a web server, database, and front-end application. We’ll use Flask for the backend, SQLte, and HTML/JavaScript for the frontend.

Backend (Flask)

from flask import Flask, jsonify
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

app = Flask(__name__)

# Setup the database connection
engine = create_engine('sqlite:///stocks.db')
Session = sessionmaker(bind=engine)
session = Session()

@app.route('/stocks')
def get_stocks():
    stocks = session.query(Stock).all()
    return jsonify([stock.to_dict() for stock in stocks])

if __name__ == '__main__':
    app.run(debug=True)

Frontend (HTML/JavaScript)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Stock Simulator</title>
    <script>
        async function fetchStocks() {
            const response = await fetch('/stocks');
            const stocks = await response.json();
            const stocksList = document.getElementById('stocksList');
            stocksList.innerHTML = '';
            stocks.forEach(stock => {
                const listItem = document.createElement('li');
                listItem.textContent = `${stock.symbol}: $${stock.price}`;
                stocksList.appendChild(listItem);
            });
        }

        document.addEventListener('DOMContentLoaded', fetchStocks);
    </script>
</head>
<body>
    <h1>Stock Simulator</h1>
    <ul id="stocksList"></ul>
</body>
</html>

Simultaneous Use and Updates

Our deployment plan includes enabling multiple users to interact with the simulator simultaneously. This involves setting up a deployment with aws and insuring db secrity, ensuring API endpoints are efficient, and handling multiple requests effectively.

© 2024    •  Powered by Soopr   •  Theme  Moonwalk