My Journey from Concept to Real-Time Price Updates
As someone eager to put my newly acquired skills to the test and also challenge myself, I decided to build a stock trading app using a microframework called Flask. This project taught me so much about web development, using APIs, and working with real-time data. In this post, I’ll walk you through my development process, highlighting key features challengest and lessons learnt along the way.
Understanding the Project’s Core: Flask framework and Real-time Updates
For this project, I chose Flask as my web framework. Flask’s simplicity and flexibility made it an ideal choice, especially since I wanted to focus on building a functional app without the complexity of a larger framework like Django.
The core functionality of my app involves fetching real-time stock data for users to view and trade. To achieve this, I used the yfinance
Python library, which pulls data directly from Yahoo Finance. This made it easy to get stock prices, symbols, and historical data without needing to deal with overly complex APIs.
import yfinance as yf
def lookup(symbol):
try:
stock = yf.Ticker(symbol)
price = stock.history(period="1d")["Close"][0]
return {"price": round(price, 2), "symbol": symbol.upper()}
except Exception:
return None
With just a few lines of code, I could retrieve the latest stock price for any given symbol. This was a huge win and made the core functionality of the app possible.
Key Features of the App
The app I built allows users to:
- Look up stock prices: Users can search for a stock symbol to get its latest price.
- Buy stocks: Users can buy shares of a stock with their available cash balance.
- Sell stocks: Users can sell shares they own.
- View portfolio: The portfolio page displays all the stocks a user owns, along with the total value and available cash.
- View transaction history: The history page shows all the user’s past transactions.
@app.route("/buy", methods=["GET", "POST"])
@login_required
def buy():
"""Buy shares of stock"""
if request.method == "POST":
symbol = request.form.get("symbol")
if not symbol:
return apology("must provide symbol")
stock = lookup(request.form.get("symbol"))
if stock is None:
return apology("Invalid stock")
shares = request.form.get("shares")
if not shares or not shares.isdigit() or int(shares) <= 0:
return apology("must provide valid number of shares")
user_id = session["user_id"]
rows = db.execute(
"SELECT cash FROM users WHERE id = ?", user_id
)
cash = rows[0]["cash"]
total_cost = stock["price"] * int(shares)
if cash < total_cost:
return apology("Insufficient funds for this purchase")
db.execute(
"UPDATE users SET cash = cash - ? WHERE id = ?", total_cost, user_id
)
db. execute("""
INSERT INTO transactions (user_id, symbol, shares, price, total, transaction_type)
VALUES(?, ?, ?, ?, ?, ?)""",
user_id, symbol, int(shares), stock["price"], total_cost, "BOUGHT"
)
flash("Bought!")
return redirect("/")
return render_template("buy.html")
This process of validating the stock symbol, checking available funds, and recording the transaction was essential to making the app functional and user-friendly.
The Tools & Technologies That Helped Me Succeed
This project wouldn’t have been possible without a solid stack of tools:
- Flask: A lightweight Python framework that allowed me to rapidly prototype and implement core features like routing, authentication, and session management.
- yfinance: To retrieve up-to-date stock price information seamlessly, I used this Python library, which simplified the process of querying stock data.
- Jinja2 Templating Engine: This allowed me to dynamically render HTML and display portfolio and transaction data based on user inputs.
- SQLite Database: This allowed for data management and tracking of data as the user interacts with the web application.
https://www.canva.com/design/DAGQKx5d598/iVfDeVTsBqwjpN30D0K2Cw/watch
What’s Next?
This project helped me understand how to build secure, real-time web applications. Next, I considering about exploring deployment of the app on platforms like Heroku or Microsoft Azure. I would like to learn more about containerization using Docker.
I am also looking forward to expanding the functionality of the app, possibly by integrating more complex financial data, such as performance graphs or predictive analytics.
If you’re working on a similar project, my advice is to start small — identify key areas where dynamic updates can improve usability and focus on implementing those first. This leads to more engaging and user-friendly applications.