Build a simple stock price web app using “streamlit” and “yfinance”

Ahmed Belaaj
9 min readJan 12, 2023

--

Hi everyone, welcome to my first medium article ever. In this article, I’ll show you how to build a simple web application that retrieves and displays real-time stock prices using the Python programming language and two powerful libraries: Streamlit and yfinance. What has driven me to write this article is the fact that stock market data can be a valuable resource for investors, financial analysts, and other professionals who need to track the performance of individual stocks or entire markets. Currently, there are plenty of platforms and apps doing the job perfectly But I was telling myself “why not make my own as a part of my learning journey?” And furthermore, I decided to write this article to explain what I’ve realized through this project in a way that makes it reproducible for new learners. So let’s get started!

Streamlit is a powerful open-source framework that allows you to create interactive web apps with minimal coding. It provides a range of useful components, such as text input fields, buttons, and charts, that you can easily incorporate into your app.

Yfinance is a Python library that provides access to real-time stock data from Yahoo Finance. It allows not only to easily download historical market data from Yahoo Finance but also provides an easy-to-use interface to access market data for stocks, options, and mutual funds. It is useful for financial analysis and data visualization, and it can be integrated with other python libraries such as pandas and NumPy.

With these tools, you’ll be able to create a user-friendly interface for your stock price app and retrieve accurate, up-to-date information about a wide range of stocks.

In the following sections, I’ll walk you through the steps of building a stock price web app with Streamlit and yfinance. Together, we’ll start by setting up our development environment and installing the necessary libraries, then we’ll see you how to create a user interface and retrieve stock data from Yahoo Finance. Finally, we’ll follow some tips on how to deploy your application using Github and streamlit sharing platform. Whether you’re a beginner or an experienced developer, this tutorial will give you everything you need to create your own stock price web app in Python.

To learn how to build a simple stock price app, you can follow and code along with this step-by-step article. Or you can just fork my repo and play around with the code to fit your specific needs. You can also have a look at the deployed version to get an idea about the final result of this work.

Setting up the development environment:

  1. Install Streamlit and yfinance by running pip install streamlit and pip install yfinance in your command prompt or terminal.
  2. Note that it is preferable to install the required libraries in a virtual environment. A virtual environment is a separate, isolated Python environment that allows you to install and use different versions of libraries and packages without affecting the global Python environment on your system. This can be useful if you want to work on multiple projects that have different library dependencies, or if you want to test your code with different versions of a library. For that, you can either create one using venv module or simply use anaconda.

Start coding

In your working directory, create a new python file and import the necessary libraries in your Python script. We need:

  • The yfinance library and rename it as yf for convenience.
  • The streamlit library and rename it as st for convenience.
  • The datetime module, which provides classes for working with dates and times.
import streamlit as st
import yfinance as yf
import datetime

Use Streamlit to create a user interface for your web app. For example, you can add a Heading for the app with the text “Simple Stock Price App”. The heading will be displayed in the app as an h1 element, which is the largest heading size thanks to thest.write function.

st.write("""
# Simple Stock Price App
""")

Now, create a new form using the st.form function. The form is given the key "my_form".

form = st.form("my_form")

Inside the form, add some visual components to allow the user to customize the data he wants to display:

Add a select box to the form using the selectbox method. The select box allows the user to choose a company from a list of options. The first argument is the label that appears next to the select box, and the second argument is a tuple of options. In this case, the options are the names of various companies.

option = form.selectbox(
'Select the company you want to display stock data',
('Google', 'Apple', 'Microsoft', 'Meta', 'Tesla', 'Amazone'))

Add a select slider to the form using the select_slider method. The select slider allows the user to choose a frequency of data from a list of options. The first argument is the label that appears next to the select slider, and the second argument is a list of options. In this case, the options are various periods of time.

period = form.select_slider(
'Select a frequency of data to display',
options=['1 min','2 mins','5 mins','15 mins','30 mins','1h',
'90 mins','1 day','5 days','1 week','1 mo','3 mo'])

Always inside the form, create two columns using the columns method. The columns method takes an integer as its argument and returns a tuple of Column objects. In this case, the argument is 2, so the tuple contains two Column objects.

col1, col2 = form.columns(2)

Add a date input to the first column using the date_input method. The date input allows the user to select a start date for the stock data. The first argument is the label that appears next to the date input, and the second argument is the default date. In this case, the default date is January 1, 2010. As for the second column, add another date input component to select the end date for the stock data inspection, we leave the second argument blank so that the default date will be the system’s date.

start = col1.date_input(
"""Select the start date (format is yyyy-MM-dd)""",
datetime.date(2010, 1, 1))
end = col2.date_input(
"""Select the end date (format is yyyy-MM-dd)""")

To end with the form, use the form_submit_button method. When the user clicks the button, the display function is called with the arguments option, period, start, and end. These arguments are passed to the display function using the args argument.

form.form_submit_button("Submit", 
on_click=display(option, period, start, end),
args=(option, period, start, end)
)
This is the result of running this app after following the above instructions

To run your application locally use the command below inside your terminal.

streamlit run <NAME_OF_THE_FILE.py>

Finally, let’s implement the display function to complete our application. This function takes the variablesoption, period, start, and end defined previously (representing the user’s selections for the company, frequency of data, and start and end dates) and maps them into interpretable values by the yfinance library.

The display function then uses the yf.Ticker class to retrieve data about the selected company and stores the data in a DataFrame called tickerDf. It also uses the st.write function to display some information about the company, including its long business summary. Next, the display function uses the st.line_chart function to display the closing price and volume data for the selected time period. Finally, the code creates a Streamlit form using the st.form function and adds a select box, a slider, and two date inputs to the form. The form allows the user to make their selections and submit them to the app. When the user clicks the submit button, the display function is called and the stock data is displayed in the app.

def display(option, period, start, end):
"""
Displays stock data for the selected company, frequency of data,
and time period.

Parameters:
option (str): The name of the company.
period (str): The frequency of data to display.
start (datetime): The start date of the time period.
end (datetime): The end date of the time period.

Returns:
None
"""

Inside the function, define two dictionaries: companies and freq. The companies dictionary maps the names of the companies to their ticker symbols. The freq dictionary maps the frequency of data to a string that is recognized by the Yahoo Finance API.

    companies = {
'Google':'GOOGL',
'Apple':'AAPL',
'Microsoft':'MSFT',
'Meta':'Meta',
'Tesla':'TSLA',
'Amazone': 'AMZN'
}
freq = {
'1 min': '1m',
'2 mins': '2m',
'5 mins': '5m',
'15 mins': '15m',
'30 mins': '30m',
'1h': '1h',
'90 mins': '90m',
'1 day': '1d',
'5 days': '5d',
'1 week': '1wk',
'1 mo': '1mo',
'3 mo': '3mo'

}

Then, retrieve the ticker symbol for the selected company using the option argument and the companies dictionary and use the yf.Ticker function from the yfinance library to create a Ticker object for the selected company.

    tickerSymbol = companies[option]
tickerData = yf.Ticker(tickerSymbol)

Next, use the st.write function to display the name of the company and its long business summary. The long business summary is retrieved from the info attribute of the Ticker object.

    st.write("""### """+option)
st.write("""#### Company presentation:""")
st.write(tickerData.info['longBusinessSummary'])
An example of what the app would display when we choose “GOOGLE” as our target company in the form

The function then uses the history method of the Ticker object to retrieve stock data for the selected company and time period. The period argument and the freq dictionary are used to specify the frequency of data. The start and end arguments are used to specify the start and end dates for the data.

Finally, the function uses the st.line_chart function to display two line charts of the stock data: one for the closing price and one for the volume. The Close and Volume attributes of the tickerDf DataFrame are used to extract the data for each chart.


tickerDf = tickerData.history(period=freq[period], start=start, end=end)
st.write("""
Shown is the stock **closing price** of
"""+option+""" from """,start,""" to """,end)
st.line_chart(tickerDf.Close)
st.write("""
Shown is the stock **volume** of
"""+option+""" from """,start,""" to """,end)

st.line_chart(tickerDf.Volume)
Example of the “closing price” visualization

Note that you can see the complete source code in my GitHub repo. You can also have a look at the final output of this work here. And I you’re wondering who did I manage to deploy my app, the upcoming section is the right place for you to find an answer. 👇👇👇

Application deployment on streamlit share

Once you have completed your stock price web app, you may want to share it with others or make it available for public use. One easy way to do this is by deploying the app on the web using Streamlit’s built-in hosting capabilities.

To deploy your app, you can create a GitHub repo for your application containing the file we just created as well as a requirements.txt file including all the needed libraries for this application. Then go to share.streamlit.io, click on sign in and click on the “continue with GitHub” option to link your streamlit account to your GitHub account.

Here are the steps to deploy your app:

  1. On the share.streamlit.io website click on the “New App” button.
  2. On the next page fill in the form with the repo’s URL, the branch used for deployment as well as the Main file path.
  3. Just click on “deploy” and chill, the application may take a moment to be ready. The app will be assigned a unique URL that you can share with others.

Note that Streamlit’s hosting service is intended for small-scale apps with low traffic. If you expect your app to receive a large amount of traffic, you may need to consider alternative hosting options.

Conclusion

To warp up everything, we have learned how to use Streamlit and yfinance to build a simple stock price web app. We started by installing the necessary libraries. Then, we used Streamlit to create a form for the user to input their selections for the company, frequency of data, and start and end dates. We used yfinance to retrieve stock data for the selected company and time period and displayed the data using Streamlit’s interactive charting functions. Finally, we learned how to deploy the app on the Streamlit Share platform using a GitHub repository.

Thank you for reading. With these skills, I hope you can build your own stock price web app or modify this one to fit your specific needs. If this article was insightful for you, then I would REALLY appreciate it if you would consider giving my repository a star ⭐ on GitHub and provide me some feedback.

--

--