My next iteration was to create a front-end application, hosted on the same rpi, that would allow anyone within my local network to change the stock ticker in realtime, simply by visiting the flask endpoint.
A simple front-end that only took a few lines of code. The three user inputs correspond to the three tickers displayed on the pygame application. A user in my network can go to
192.xx.xx.xx:8082 within my local network to access this light-weight flask application.
Flask - How It Works
After a submission, the new tickers get written to a text file. The pygame application periodically checks if a modification has been made to the
ticker_files.txt file. If there is a modification, the stock ticker application reads those new tickers and pulls from the yfinance module.
A few normalization and error checking steps:
- First check if the ticker is valid by hitting the yfinance module
- Stripping unnecessary quotes
- Writing to the text file
#!/usr/bin/python3 from flask import Flask, render_template, url_for, request import yfinance as yf app = Flask(__name__) def home(): if request.method == "POST": tk1 = request.form.get("tk1") tk2 = request.form.get("tk2") tk3 = request.form.get("tk3") ticker_list = [tk1,tk2,tk3] ticker_list_names =  ticker_string = "" for t in ticker_list: t = t.upper() ticker_string += t + "," t_object = yf.Ticker(t) if t_object.info["regularMarketPrice"] == None: return "You have submitted an incorrect symbol: "+ t + ", go back and resubmit" else: ticker_list_names.append(t_object.info["shortName"].split(" ")) print(ticker_list) print(ticker_list_names) ticker_string += ticker_list_names.replace(",","") + "," ticker_string += ticker_list_names.replace(",","") + "," ticker_string += ticker_list_names.replace(",","") text_file = open("/home/pi/Desktop/ticker_files.txt","w+") text_file.writelines(ticker_string) return "You've submitted " + tk1 + " " + tk2 + " " +tk3 return render_template("home.html") def flask_run(): app.run(host='0.0.0.0',port='8082') flask_run()
This function is called every other second to check if there was a modification (by timestamp) to the text file. If there was a change, indicating that a user has submitted new tickers, the ticker symbols are returned and are used going forward to call the prices and % changes.
stamp_old = 0 def check_file_change(): global stamp_old stamp_new = os.stat("/home/pi/Desktop/ticker_files.txt").st_mtime if stamp_new != stamp_old: #file changed stamp_old = stamp_new with open("/home/pi/Desktop/ticker_files.txt","r") as f: lines = f.readlines() return lines else: return 0