Visualizing Stock Market Trends with Python

Orkun
3 min readJun 11, 2024

--

Discover how to harness the power of Python libraries like yfinance, matplotlib, and seaborn to analyze and visualize stock market data. This guide will walk you through fetching and visualizing stock prices for major companies over the last year.

Getting Started with Stock Data: Before diving into the graphs, you’ll need Python and several libraries installed. Make sure you have yfinance, matplotlib, and seaborn ready to go. You can install these packages via pip if you haven't already:

pip install yfinance matplotlib seaborn

Fetching Stock Data Using: yfinance, a popular library that allows for easy access to Yahoo Finance's data, we will fetch the closing prices for Apple (AAPL), Microsoft (MSFT), and Google (GOOGL) from January 1, 2023, to January 1, 2024.

Visualizing Data with Matplotlib and Seaborn

Stock Closing Prices Comparison: Let’s start by comparing the closing prices of these stocks over the year. This line graph provides a clear visual representation of how each stock has performed relative to others.

import matplotlib.pyplot as plt

plt.figure(figsize=(14, 7))
for symbol in stock_symbols:
plt.plot(data['Close'][symbol], label=symbol)

plt.title('Stock Closing Prices Comparison')
plt.xlabel('Date')
plt.ylabel('Closing Price (USD)')
plt.legend()
plt.grid(True)
plt.show()

Bar Plot of Latest Closing Prices: Next, we’ll create a bar plot that shows the closing prices of the stocks on the last date of the dataset. This gives us a snapshot of their performance at year-end.

last_date = data.index[-1]
closing_prices = [data['Close'][symbol].loc[last_date] for symbol in stock_symbols]

plt.figure(figsize=(14, 7))
plt.bar(stock_symbols, closing_prices, color=['blue', 'green', 'red'])

plt.title(f'Stock Closing Prices Comparison on {last_date.date()}')
plt.xlabel('Stock Symbol')
plt.ylabel('Closing Price (USD)')
plt.show()

Scatter Plot for Price Relationship: Understanding the relationship between two stocks can be pivotal. Here’s how the closing prices of AAPL and MSFT relate to each other.

stock1 = stock_symbols[0]
stock2 = stock_symbols[1]

plt.figure(figsize=(14, 7))
plt.scatter(data['Close'][stock1], data['Close'][stock2])

plt.title(f'Closing Price Relationship between {stock1} and {stock2}')
plt.xlabel(f'{stock1} Closing Price (USD)')
plt.ylabel(f'{stock2} Closing Price (USD)')
plt.grid(True)
plt.show()

Histogram of AAPL Closing Prices: Analyzing the distribution of Apple’s closing prices over the year can provide insights into its volatility and stability.

stock = stock_symbols[0]

plt.figure(figsize=(14, 7))
plt.hist(data['Close'][stock], bins=30, color='blue', alpha=0.7)

plt.title(f'Distribution of {stock} Closing Prices')
plt.xlabel('Closing Price (USD)')
plt.ylabel('Frequency')
plt.grid(True)
plt.show()

Heatmap of Stock Correlations: Finally, using seaborn, we'll create a heatmap to visualize the correlation between the closing prices of these stocks. This helps identify how closely the movements of these stocks are related.

import seaborn as sns
correlation_matrix = data['Close'][stock_symbols].corr()

plt.figure(figsize=(14, 7))
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', vmin=-1, vmax=1)

plt.title('Correlation Matrix of Stock Closing Prices')
plt.show()

Conclusion

Visualizing stock market data not only aids in understanding past performance but also helps in predicting future trends. Python’s libraries offer powerful tools to make this task easier and more insightful. Whether you are a seasoned investor or a novice looking to understand the market, these tools can provide valuable insights into the complex world of stocks.

--

--

No responses yet