Tracking Stock Prices
You've now built your first Flask application! In this next section, we're going to build upon this to create a web application for more than just dice rolling which we will deploy to the internet. Over the next few chapters we are going to extend this application further to add more functionality and explore more parts of Flask.
What we're building
Some people like tracking the price of stocks, but if you go to many stock websites, there's a lot of clutter and the largest piece of information that people care about (the stock price) is not obvious. With our Python and Flask skills, we can make an application to solve that problem.
Setting up.
In our terminal, let's go back to our fullstack-flask folder and create a new folder for our app (which we can call stock-app
)
cd ~/fullstack-flask
mkdir stock-app
cd stock-app
Again, we're going to set up a virtual environment.
python3 -m venv env
source env/bin/activate
This time, to install Flask, we're going to create a file called requirements.txt where we list all of the dependencies of our project
touch requirements.txt
We're also going to use a Python library called requests
to interface with an external API to fetch the data we need about stocks.
Put these lines in your file requirements.txt
:
Flask
requests
Once we've set up this file, we can install the requirements using pip by running
pip install -r requirements.txt
Then we're going to create a server.py
to start out our Flask application.
touch server.py
code . # optional: to open the folder in VS Code
Within server.py, we're going to repeat the Flask imports to initialize our Flask application. This time in addition to importing Flask, we're going to import requests
, a Python library to make HTTP requests.
from flask import Flask
app = Flask(__name__)
We will also need a free API key from FinancialModelingPrep.com to get access to the raw data. You can register for your own API key for free at https://financialmodelingprep.com/developer/docs/.
warning
The free API provided by FinancialModelingPrep.com requires an API key for usage. When we pass the URL parameters of apikey=demo
, the API only works for Apple's stock.
This free API key will give you a certain amount of free requests everyday. When you get your own API key, you will need to change the usage of 'demo'
in our code to be your own API key. You don't have to register for one if you only want to use the price of AAPL, you can just use the demo
API key.
Thinking about our Flask Application design
When building Flask applications, it is helpful to think about the URL structure of your final product. For the first version of our stock ticker application, we might want two endpoints if our application was hosted at FlaskFinance.com.
If we hit the root page of the application (FlaskFinance.com), we would want to see the prices of our favorite stocks, and there might be another page to render just the price of a single stock (for example FlaskFinance.com/stocks/APPL or FlaskFinance.com/stocks/GOOG)
Once we have an idea for what the routes should look like, Flask makes it easy to define these. We'll dive deeper into routing in a later chapter. We've already seen an example for the decorator for the index page (@app.route('/')
) but to accept an arbitrary string like we would need to for FlaskFinance.com/stocks/AAPL, we can tell Flask to expect a parameter by @app.route('/stocks/<ticker>')
, and then Flask will pass in an argument into the function based on what followed the in the URL path. For FlaskFinance.com/stocks/AAPL
, the value of ticker
would be AAPL
.
Every route we define needs to point to a different function that will handle requests to that route. Let's create two routes in server.py
for this.
@app.route('/')
def home():
return "This is the home page. Try going to /stocks/AAPL"
@app.route('/stocks/<ticker>')
def stock(ticker):
return "This is the page for the {} ticker".format(ticker)
We can try this in our browser by launching the Flask development server and see what we get.
FLASK_ENV=development FLASK_APP=server flask run
Your terminal output should look something like this:
Once your server is running you can pull up a page at 127.0.0.1:5000/stocks/AAPL
Now, we should try to get the actual prices of stocks using the API.
Let's write a function to fetch data from the API endpoint. I've already written it out here, and you can use it.
def fetch_price(ticker):
data = requests.get('https://financialmodelingprep.com/api/v3/stock/real-time-price/{}'.format(ticker.upper()), params={'apikey': 'demo'}).json()
return data["price"]
What this does: Issues a HTTP request to an API provided by financialmodelingprep.com which returns the price of the stock as a JSON object. Our function returns the price as a numeric value.
Once we have that we can integrate the fetch_price
function into our stock
function.
@app.route('/stocks/<ticker>')
def stock(ticker):
stock_price = fetch_price(ticker)
return "The price of {} is {}".format(ticker, stock_price)
Now if launch our Flask server and navigate to 127.0.0.1:5000/stocks/AAPL
FLASK_ENV=development FLASK_APP=server flask run
We should see the actual price of AAPL
in our browser.