The world’s leading publication for data science, AI, and ML professionals.

Building a Data App with Streamlit in No Time

A practical guide for creating a stock price application

Streamlit data app (GIF by author)
Streamlit data app (GIF by author)

Note from Towards Data Science‘s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.


When I started my journey in data science, I did not have a clue about deploying models or creating web applications. My data science world was bounded by jupyter notebooks.

After a while, it became crystal clear to me that I needed to go beyond the notebooks. Whatever I did with the data, it somehow needed to be turned into a product so that other people could test it or use it. That’s when I started learning about deploying models and creating data applications.

Even if you create a state-of-the-art model, it creates no value when sitting in a jupyter notebook. You may create a brilliant data app but it is only valuable if other people use it.

Thus, creating products and maintaining them are very critical steps in the field of data science.

Streamlit makes it fairly easy to convert your data scripts into a web app. You do not have to have front-end experience. All you need is Python.

In this post, we will create a simple stock price data app. It will extract and demonstrate stock prices based on some user inputs.

We will use a text editor to write the script (I use sublime). Make sure you have Python 3.6 or a later version installed in your computer.

The dependencies that we need can be installed from the terminal with pip:

pip install streamlit
pip install pandas
pip install pandas-datareader
pip install datetime

Let’s start building our app.

The first step is to import the dependencies:

import pandas as pd
import streamlit as st
from pandas_datareader import data
from datetime import datetime, timedelta

We can display a title for our app:

st.title("Streamlit Stock Prices App")

The next step is to retrieve the data. We will use the pandas-datareader module to get stock price data. It requires three inputs which are the stock name, start date, and end date.

We will ask the user to input these parameters. Streamlit provides many different ways to collect user input.

We will use the text_input widget to ask the users for the stock name:

stock_name = st.text_input("Enter the stock name: n")

For the start and end dates, we will ask the users how many days of data they want to see using a slider widget.

option = st.slider("How many days of data would you like to see?",
      1,60,1)

The number parameters are start, end, and the step size.

These widgets will be seen in the app as follows:

(image by author)
(image by author)

We will use the datetime module to create a start date and end date based on the user input.

end = datetime.today().strftime('%Y-%m-%d')
start = (datetime.today() - timedelta(option)).strftime('%Y-%m-%d')

We take today as the end date. The start date is calculated by going back for the number of days given by the user. For instance, if the option is given as 20 days, the data will show the stock prices of the past 20 days.

The next step is to define a function that collects the data based on these inputs.

def load_data(stock, start_date, end_date):
    df = data.DataReader(name=stock,
                         start=start_date,
                         end=end_date,
                         data_source='yahoo')
    return df

The load_data function will create a pandas dataframe that contains the stock prices based on the given inputs.

Before we call the function, we will display a text describing the state of the operation.

data_load_state = st.text("Loading data...")

Users will see "Loading data…" while the app is working on the data.

The next step is to call the function and create a pandas dataframe.

df = load_data(stock=stock_name, start_date=start, end_date=end)
df.sort_index(axis=0, inplace=True, ascending=False)

We now have the data stored in a dataframe. We have many options for displaying the data to the user. Streamlit provides a wide range of charts. For instance, a line chart that shows the prices over time can be useful.

We are not limited to the charts provided by Streamlit. We can even run a Machine Learning model to make predictions on the following days.

For the sake of simplicity, I will display the dataframe and a line chart:

st.subheader(f'{stock_name} stock prices for the past {option} days')
st.dataframe(df)

chart_data = df[['Close']]
st.subheader("Close Prices")
st.line_chart(chart_data)

The names make it seem pretty obvious. We use st.dataframe() to display the dataframe and st.line_chart() to create line chart. The st.subheader() allows adding a title to the displayed objects.

The final step is to change the state of the displayed text while the app is working on the data. As you may recall the text was "Loading data…". The following code will change it as "Data Loaded!".

data_load_state.text("Data loaded!")

Here is a screenshot of the entire script.

(image by author)
(image by author)

You may have notice that we use "@st.cache" before the function definition. What it does is that it runs the function and stores the result in a local cache. Thus, if the function is called again with exactly same parameters, streamlit reads the output from the local cache instead of running the function again.

Our script is complete now. We will save it in the current working directory as a python file and then use the command line to run the script. The command is:

streamlit run "file_name"
(image by author)
(image by author)

When streamlit executes the script, a new tab in the browser will be opened.

(image by author)
(image by author)

Our data app is complete now. Please note that it is currently running on your local machine. Thus, only you can experiment with the app.

In the following article, I will write about how to run the app on an AWS EC2 instance. After that, you will be able to share your app with your friends.


Conclusion

We have created a simple app that does a simple task. However, the procedure of creating complex apps are pretty similar.

The biggest advantage of using streamlit is that everything is done with Python. Most, if not all, data scientists are familiar with Python so it will not be difficult for them to adapt Streamlit.

As with any other subject, practice makes perfect. I recommend working on simple apps first. You can then steadily increase the complexity of your projects.

Thank you for reading. Please let me know if you have any feedback.


Related Articles