Real-time Apple Stock Prices Visualization using yfinance and Streamlit

Sohail Hosseini
3 min readJun 27, 2023

Python, with its rich ecosystem of libraries, allows for the development of incredibly sophisticated and intricate applications. In this article, we will take a deep dive into one such application, which uses the ‘yfinance’ library to fetch stock data, and ‘Streamlit’, a popular framework for building data apps, to visualize this data in real-time.

Prerequisites

Before we start, ensure that you have the required Python libraries installed on your system. If not, you can install them using pip:

pip install yfinance streamlit matplotlib

Overview of the Code

The objective of this application is to provide real-time visualizations of Apple’s stock prices. The code has been written in a file named ‘test.py’. Let’s dissect the code section by section:

Importing Necessary Libraries

import streamlit as st
import yfinance as yf
import matplotlib.pyplot as plt
import time

The first section of the code imports all the required libraries. ‘streamlit’ is used to build the data app, ‘yfinance’ to fetch stock data, ‘matplotlib’ to create plots, and ‘time’ to create delays in our infinite loop.

Setting up Streamlit

st.title("Real-time Apple Stock Prices")

This line sets the title of our Streamlit app to ‘Real-time Apple Stock Prices’.

Fetching Stock Data

# Define the ticker symbol for Apple
ticker_symbol = 'AAPL'

# Get the data of the stock
apple_stock = yf.Ticker(ticker_symbol)

Here, we define the ticker symbol for Apple, which is ‘AAPL’. Using yfinance’s Ticker function, we fetch the data of Apple's stock.

Creating a Matplotlib Figure

# Create a matplotlib figure
fig, ax = plt.subplots()

# Use st.pyplot to display the plot
plot = st.pyplot(fig)

We then create a Matplotlib figure where we’ll plot our data. We also use Streamlit’s pyplot function to display the plot in the app.

Infinite Loop to Fetch and Update Stock Values

# Loop to fetch and update stock values
while True:
# Get the historical prices for Apple stock
historical_prices = apple_stock.history(period='1d', interval='1m')

# Get the latest price and time
latest_price = historical_prices['Close'].iloc[-1]
latest_time = historical_prices.index[-1].strftime('%H:%M:%S')

# Clear the plot and plot the new data
ax.clear()
ax.plot(historical_prices.index, historical_prices['Close'], label='Stock Value')
ax.set_xlabel('Time')
ax.set_ylabel('Stock Value')
ax.set_title('Apple Stock Value')
ax.legend(loc='upper left')
ax.tick_params(axis='x', rotation=45)

# Update the plot in the Streamlit app
plot.pyplot(fig)

# Show the latest stock value in the app
st.write(f"Latest Price ({latest_time}): {latest_price}")

# Sleep for 1 minute before fetching new data
time.sleep(60)

In this section, we have an infinite loop that continuously fetches and updates Apple’s stock values. Inside the loop, we first get the historical prices for the stock for the current day at a 1-minute interval.

We then retrieve the latest stock price and the corresponding time. Following this, we clear our Matplotlib plot, plot the new data, and set the necessary plot details.

Then, we use Streamlit’s pyplot function to update the plot in the app and display the latest stock value. Finally, we put the loop to sleep for 60 seconds before it starts fetching new data again.

Running the App

You can run the Streamlit app using the following command in your terminal:

streamlit run test.py

Upon execution, the script will pull the real-time data of Apple’s stock prices every minute and visualize it on a line graph, which gets updated dynamically. The latest stock price and time will also be displayed.

Apple Stock Prices

Conclusion

This application is an excellent example of the power of Python and its libraries. yfinance allows us to fetch real-time stock data, while Streamlit provides an easy and intuitive way to visualize this data. Such applications can serve as a starting point for building more complex financial analytics and visualization tools.

BECOME a WRITER at MLearning.ai // text-to-video // Divine Code

--

--