# Importing libraries
import yfinance as yf
import pandas as pd
import numpy as np
import plotly.io as pio
import plotly.express as px
# Set plot style
pio.templates.default = "seaborn"
# Loading stock data in bulk; keeping only dates with values across all ticker symbols
stock_data = yf.download('MSFT AAPL SONY META GME AMZN TSLA', period='max').dropna()
benchmark_data = data = yf.download('^GSPC', period='max').dropna()
stock_data = stock_data['Close']
stock_data.head()
benchmark_data = benchmark_data[['Close']].rename(columns={'Close':'S&P 500'})
benchmark_data.head()
# Visualization of stock data
fig = px.line(stock_data,
title='Stock Data',
labels={'value':'$ USD',
'variable':'Ticker'})
fig.show()
# Summary of stock data
stock_data.info()
# Visualization of benchmark data
fig = px.line(benchmark_data,
title='Benchmark Data - S&P 500',
labels={'value':'$ USD'})
fig.update_layout(showlegend=False)
fig.show()
# Summary of benchmark data
benchmark_data.describe()
stock_returns = stock_data.pct_change()
fig = px.line(stock_returns,
title='Stock % Change',
labels={'variable':'Ticker'})
fig.show()
stock_returns.describe()
# sp_returns will be a series to facilitate calculations
sp_returns = benchmark_data['S&P 500'].pct_change()
fig = px.line(sp_returns, title='S&P 500 % Change')
fig.update_layout(showlegend=False)
fig.show()
benchmark_data.describe()
excess_returns = stock_returns.sub(sp_returns, axis=0).dropna()
fig = px.line(excess_returns, labels={'variable':'Ticker'}, title='Excess Returns')
fig.show()
excess_returns.describe()
avg_excess_return = excess_returns.mean()
fig = px.bar(avg_excess_return, color=avg_excess_return.index)
fig.update_layout(showlegend=False, title='Average Excess Returns')
fig.show()
sd_excess_return = excess_returns.std()
fig = px.bar(sd_excess_return, color=sd_excess_return.index)
fig.update_layout(showlegend=False, title='Standard Deviation of the Return Difference')
fig.show()
daily_sharpe_ratio = avg_excess_return.div(sd_excess_return)
# annualized Sharpe ratio for trading days in a year (5 days, 52 weeks, no holidays)
annual_factor = np.sqrt(252)
annual_sharpe_ratio = daily_sharpe_ratio.mul(annual_factor)
fig = px.bar(annual_sharpe_ratio, color=annual_sharpe_ratio.index)
fig.update_layout(showlegend=False, title='Annualized Sharpe Ratio: Stocks vs S&P 500')
fig.show()