Skip to content

Instantly share code, notes, and snippets.

@fsndzomga
Created February 19, 2024 04:54
Show Gist options
  • Save fsndzomga/9f7bb1c05eec8d25d6a7a22bcd939b52 to your computer and use it in GitHub Desktop.
Save fsndzomga/9f7bb1c05eec8d25d6a7a22bcd939b52 to your computer and use it in GitHub Desktop.
import yfinance as yf
import pandas as pd
# Define tickers by sector
sectors = {
'Technology': ['AAPL', 'MSFT', 'GOOGL'],
'Healthcare': ['JNJ', 'PFE', 'MRK'],
'Consumer Discretionary': ['AMZN', 'TSLA', 'MCD']
}
# Define a dictionary to hold our data
sector_performance = {}
# Fetch YTD performance for each stock and calculate average sector performance
for sector, tickers in sectors.items():
# Fetch data
data = yf.download(tickers, period='ytd')['Adj Close']
# Calculate YTD return
ytd_returns = data.pct_change().sum()
# Calculate average performance of the sector
sector_performance[sector] = ytd_returns.mean()
# Convert to DataFrame for better visualization
sector_performance_df = pd.DataFrame(list(sector_performance.items()), columns=['Sector', 'Average YTD Return'])
print(sector_performance_df)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment