In the vast landscape of financial markets, understanding the historical performance of stocks is essential. In this blog post, we'll embark on a journey to analyze stock data for two tech giants, Apple Inc. (AAPL) and Microsoft Corporation (MSFT). Using Python and financial data from Yahoo Finance, we'll explore descriptive statistics, dispersion measures, and visualize the relationships through line plots and heatmaps.
Fetching and Exploring Stock Data
Let's start by fetching historical stock data for Apple and Microsoft and exploring the dataset.
import yfinance as yf
import pandas as pd
import numpy as np
# Fetch historical stock data for Apple and Microsoft
symbols = ['AAPL', 'MSFT']
start_date = '2020-01-01'
end_date = '2023-01-01'
try:
stock_data = yf.download(symbols, start=start_date, end=end_date, progress=False)
# Check if data is available
if stock_data.empty:
raise Exception('No price data found for the specified stocks and date range.')
# Display the first few rows of the dataset
print(stock_data.head())
except Exception as e:
print(f"Error: {e}")
Visualizing Historical Closing Prices
Let's visualize the historical closing prices of Apple and Microsoft using line plots.
import matplotlib.pyplot as plt
# Line plot for closing prices
plt.figure(figsize=(12, 6))
for symbol in symbols:
plt.plot(stock_data['Close'][symbol], label=symbol, linewidth=2)
plt.title('Historical Closing Prices of Apple and Microsoft')
plt.xlabel('Date')
plt.ylabel('Closing Price (USD)')
plt.legend()
plt.show()
Descriptive Statistics and Dispersion Measures
Now, let's calculate descriptive statistics, standard deviation, and variance for a deeper understanding.
# Descriptive statistics
descriptive_stats = stock_data.describe()
print("\nDescriptive Statistics:")
print(descriptive_stats)
# Dispersion measures (Standard Deviation and Variance)
std_dev = stock_data.std()
variance = stock_data.var()
print("\nStandard Deviation:")
print(std_dev)
print("\nVariance:")
print(variance)
Correlation and Covariance
Explore the relationships between Apple and Microsoft stocks through correlation and covariance.
# Correlation
correlation_matrix = stock_data['Close'].corr()
print("\nCorrelation Matrix:")
print(correlation_matrix)
# Covariance Matrix
covariance_matrix = stock_data['Close'].cov()
print("\nCovariance Matrix:")
print(covariance_matrix)
Visualizing Correlation with a Heatmap
Let's visualize the correlation matrix with a heatmap.
import seaborn as sns
# Heatmap for correlation matrix
plt.figure(figsize=(10, 8))
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', fmt=".2f", linewidths=0.5)
plt.title('Correlation Heatmap of Closing Prices')
plt.show()
Conclusion
Analyzing stock data provides valuable insights for investors and analysts. In this exploration, we fetched historical stock data for Apple and Microsoft, visualized closing prices, and delved into descriptive statistics, dispersion measures, correlation, and covariance. Python, with libraries like yfinance
, pandas
, numpy
, matplotlib
, and seaborn
, serves as a powerful tool for financial data analysis. As you navigate the financial landscape, these techniques will empower you to make informed decisions and gain deeper insights into market dynamics. Happy analyzing!
Top comments (0)