import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
#top 10 market value 20240614
top_10_companies = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'NVDA', 'META', 'TSLA', 'BRK-B', 'JNJ', 'JPM']
#past 91 days price data
data = yf.download(top_10_companies, period='91d')
#adjusted close prices
adj_close = data['Adj Close']
#total percentage change
total_change = ((adj_close.iloc[-1] - adj_close.iloc[0]) / adj_close.iloc[0]) * 100
#Plot bar
plt.figure(figsize=(10, 6))
bars = total_change.sort_values().plot(kind='bar', color='skyblue')
plt.title('Total Percentage Change in Past 91 Days')
plt.xlabel('Company')
plt.ylabel('Total Percentage Change')
#Annotate
for bar in bars.patches:
bars.annotate(f'{bar.get_height():.2f}%',
(bar.get_x() + bar.get_width() / 2, bar.get_height()),
ha='center', va='bottom')
plt.show()
#Calculate cumulative returns
cumulative_returns = (adj_close / adj_close.iloc[0]) - 1
#Plot the cumulative returns
plt.figure(figsize=(14, 8))
for company in top_10_companies:
plt.plot(cumulative_returns[company], label=company)
#Annotate
for company in top_10_companies:
y = cumulative_returns[company].iloc[-1]
plt.annotate(f'{y*100:.2f}%',
xy=(cumulative_returns.index[-1], y),
xytext=(10, 0),
textcoords='offset points',
horizontalalignment='left', verticalalignment='center',
fontsize=9, bbox=dict(facecolor='white', edgecolor='none', alpha=0.7))
plt.title('Cumulative Returns in the Past 91 Days')
plt.xlabel('Date')
plt.ylabel('Cumulative Returns')
plt.legend()
plt.show()
#Calculate daily returns
daily_returns = (adj_close/adj_close.shift(1))-1
daily_returns=daily_returns.dropna()
#Calculate correlation matrix
correlation_matrix = daily_returns.corr()
#Plot heatmap
fig, ax = plt.subplots(figsize=(12, 8))
cax = ax.matshow(correlation_matrix, cmap='coolwarm', vmin=-1, vmax=1)
fig.colorbar(cax)
#Set labels
ax.set_xticks(range(len(correlation_matrix.columns)))
ax.set_yticks(range(len(correlation_matrix.index)))
ax.set_xticklabels(correlation_matrix.columns, rotation=90)
ax.set_yticklabels(correlation_matrix.index)
#Annotate
for (i, j), val in np.ndenumerate(correlation_matrix):
ax.text(j, i, f'{val:.2f}', ha='center', va='center', color='black')
plt.title('Correlation Heatmap of Daily Returns')
plt.show()