Created
February 19, 2024 04:35
-
-
Save fsndzomga/857557eee7c03aa86f1d10948c3065bd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import yfinance as yf | |
import pandas as pd | |
import matplotlib.pyplot as plt | |
# Define the ticker symbols for the stock and the benchmark index | |
stock_symbol = 'AAPL' | |
benchmark_symbol = '^GSPC' | |
# Fetch historical data for the past year | |
stock_data = yf.download(stock_symbol, start='2023-01-01', end='2024-01-01') | |
benchmark_data = yf.download(benchmark_symbol, start='2023-01-01', end='2024-01-01') | |
# Calculate daily returns | |
stock_data['Daily Return'] = stock_data['Adj Close'].pct_change() | |
benchmark_data['Daily Return'] = benchmark_data['Adj Close'].pct_change() | |
# Calculate cumulative returns | |
stock_data['Cumulative Return'] = (1 + stock_data['Daily Return']).cumprod() | |
benchmark_data['Cumulative Return'] = (1 + benchmark_data['Daily Return']).cumprod() | |
# Plot the cumulative returns | |
plt.figure(figsize=(14, 7)) | |
plt.plot(stock_data['Cumulative Return'], label=f'{stock_symbol} Cumulative Return') | |
plt.plot(benchmark_data['Cumulative Return'], label=f'{benchmark_symbol} Cumulative Return') | |
plt.title('Stock vs. Benchmark Cumulative Returns') | |
plt.xlabel('Date') | |
plt.ylabel('Cumulative Return') | |
plt.legend() | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment