Creating A Stock Dashboard with Streamlit


As a data analyst at a financial services company, I am constantly retrieving data for internal and external clients. The process typically boils down to writing ad-hoc sql queries tailored to a specific client’s needs. This can sometimes be lengthy and repetitive, and I would often ask myself how to automate as much of it as possible in order to empower others to get data through self-service.

Enter Streamlit. Streamlit is a python package devoted to building user-friendly business intelligence applications, enabling users to easily retrieve the exact data they want. I like to think of it as Python’s version of Tableau (Python also has a Tableau package, TabPy), except it’s free and more importantly, democratizes data analysis, allowing everyone to find what they are looking for.

I chose to focus on stocks because there is a plethora of publicly available data and they have an impact on many people’s financial well-being. But you can apply this tutorial to any dataset you want!

Getting Started:

To build our stock dashboard, we’ll first need to install streamlit and iexfinance, an api that retrieves stock data. Open your terminal or command prompt and type the following:

pip install streamlit 
pip install iexfinance

Next, download the stock ticker file from my GitHub and save it as ticker_data.csv:

After that, open your favorite text editor (I like Atom or Visual Studio Code) and create a new file,

Writing the Code:

After we’ve created our python file, we are ready to start coding! First, import the necessary packages (simply pip install any of these packages that you might not have):

#import packages 
from datetime import datetime
from iexfinance.stocks import get_historical_data
import pandas as pd
import streamlit as st
import as px
import plotly.graph_objects as go
import yfinance as yf
from plotly.subplots import make_subplots

Next we create a date range and load our stock ticker file. This file will be used to populate a menu of stocks that a user can a user can choose from:

#create date range 
start = datetime(2019, 1, 1) end =
#get ticker data
ticker_df = pd.read_csv('ticker_data.csv')
tickers = ticker_df.Symbol.values.tolist()

After we’ve written our preliminary lines of code, let’s start making our dashboard! Type the following:

#create title for dashboard st.title('Finance Portal') #create sidebar with options

sidebar = st.sidebar.selectbox('Select an Option',['Stocks', 'Crypto','Fixed Income'])

We created a title for our dashboard and also a sidebar with options, allowing users to retrieve stock, fixed income or crypto related data. For the sake of this article, we’ll only focus on the stock portion. Finally, to see what your dashboard looks like so far, open a terminal and change to the directory where you saved the python script and type the following, which will launch a web-browser page with your dashboard:

#change directories, if needed cd your directory #Activate your dashboard 
streamlit run

Now let’s populate our dashboard with some data! Let’s begin with the following:

if sidebar == 'Stocks': 
exchange ='select an exchange or Ticker', ['S&P 500', 'Nasdaq', 'Search by Ticker'])
if exchange == 'S&P 500':
dropdown = st.selectbox('Select a Ticker', tickers)
df = get_historical_data( dropdown, start, end, output_format='pandas', token='YOUR API key')
fig = px.line(df, x=df.index, y=df.close, title=str(dropdown)+' 2019 Performance')

Breaking this down, on the stock page we are creating three buttons that filter the universe of stocks from which a user can select. Next, a dropdown menu is created with a list of stocks to browse, based on the chosen exchange. Data is then fetched and put into a pandas data frame and then displayed in a graph (remember to provide your api token, which IEX provides, in the token argument of the get_historical_data function).

Let’s refresh our webpage (Hello, Data!). You’ll now be able to search any publicly traded stock you’d like and see it’s 2019 performance.

We can now visually see a stock’s performance for the year. Let’s now put an exact number on it. Below the plotly_chart(fig) line, under the S&P 500 section, type the following:

first_value = df.close.iloc[0] 
last_value = df.close.iloc[-1]
change = (last_value - first_value)/first_value
if change > 0:
st.write("This stock was up {:.2f}".format(change)+ '%')
elif change < 0:
st.write("This stock was down {:.2f}".format(change)+ '%')

To quickly summarize, we get the first and last price observations for our chosen stock and compute the percentage change, which will be displayed below our graph. Let’s quickly refresh our dashboard to see the change:

Finally, let’s add one last bit to our dashboard. Investment performance is bench-marked by the market’s performance as a whole, typically the S&P 500. To measure our stock’s performance against the S&P 500, we need to fetch S&P 500 data, which cannot be done with iexfinace, last time I checked. We’ll use yfinance-yahoo finance-instead.

Let’s create a sub-header to our page and use yfinance to retrieve the data:

#create subheader 
st.subheader('Did Your Stock Beat the market?')
#get S&P 500 data
df2 ='%5EGSPC', start=start, end=end)

After we’ve retrieved the S&P 500 data, we calculate its performance for the year, graph it and then compare it to our stock:

#first observation sp_perf_1 = df2.Close.iloc[0] 
#last observation sp_perf_last = df2.Close.iloc[-1]
#calculate %
change sp_perf = (sp_perf_last-sp_perf_1)/sp_perf_1
#graph data
perf_graph = make_subplots(specs=[[{"secondary_y": True}]]) perf_graph.add_trace(go.Scatter(x=df2.index, y=df2.Close, mode='lines', name='S&P 500'),secondary_y=False)
perf_graph.add_trace(go.Scatter(x=df.index, y=df.close, mode='lines', name=dropdown),secondary_y=True) #display graph #display chart
st.plotly_chart(perf_graph) #display percentage change st.write("S&P's Performance: {:.2f} ".format(sp_perf)) st.write(dropdown + "'s performance: {:.2f} ".format(change))

Refresh the page one last time, and voila! We now have a fully functional dashboard!

I hope you found this helpful and please add more content to the dashboard. This is only the beginning!

Originally published at

Stumbled into a data-centric role several years ago and have not looked back! Passionate about leveraging technology to uncover answers and improve the world.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store