Analyzing Close Prices of Popular ETFs Using Python and Yahoo Finance API

In this blog article, we will walk through a simple Python script that uses the yfinance and pandas libraries to download and analyze historical stock market data. We will focus on five popular exchange-traded funds (ETFs) – SPY, BND, GLD, QQQ, and VTI – and display their close prices over the past two years. This script can be easily modified to analyze other financial instruments or timeframes.

Section 1: Define Tickers and Time Range

First, we need to define the list of ETF tickers that we want to analyze. In this example, we will analyze the following five ETFs: SPY, BND, GLD, QQQ, and VTI. We will also set the start and end dates for our analysis. The end date will be set to today’s date, and the start date will be set to two years ago.

				
					import yfinance as yf
from datetime import datetime, timedelta

# Define the list of tickers
tickers = ['SPY', 'BND', 'GLD', 'QQQ', 'VTI']

# Set the end date to today
end_date = datetime.today()
print(end_date)

# Set the start date to 2 years ago
start_date = end_date - timedelta(days=2 * 365)
print(start_date)

				
			

Section 2: Download Close Prices

Next, we will download the close prices for each ticker in our list. We will create an empty DataFrame to store the close prices and then use the yf.download() function to fetch the data for each ticker. Finally, we will display the DataFrame containing the close prices.

				
					import pandas as pd

# Create an empty DataFrame to store the close prices
close_df = pd.DataFrame()

# Download the close prices for each ticker
for ticker in tickers:
    data = yf.download(ticker, start=start_date, end=end_date)
    close_df[ticker] = data['Close']

# Display the DataFrame
print(close_df)

				
			

After running this code, you should have a DataFrame containing the historical close prices for each of the ETFs in the specified date range. You can now use this data for further analysis, such as calculating returns, plotting price trends, or developing trading strategies. 

Section 3: Calculating Returns

Now that we have our DataFrame containing the historical close prices, let’s calculate the daily returns for each ETF. To do this, we will use the pct_change() function from the pandas library, which computes the percentage change between the current and prior element.

				
					# Calculate daily returns
daily_returns = close_df.pct_change()

# Display the daily returns DataFrame
print(daily_returns)

				
			

Section 4: Plotting Price Trends

To visualize the price trends of our selected ETFs, we can create a line chart using the plot() function from the pandas library. This will allow us to quickly identify trends and patterns in the historical price data.

				
					import matplotlib.pyplot as plt

# Plot the historical close prices
close_df.plot(figsize=(10, 6))
plt.title('Historical Close Prices of Popular ETFs')
plt.xlabel('Date')
plt.ylabel('Close Price')
plt.legend(loc='upper left')
plt.show()

				
			

Section 5: Developing Trading Strategies

With the historical price data and daily returns in hand, you can now develop and test trading strategies based on your analysis. For example, you might create a moving average crossover strategy to generate buy and sell signals. In this example, we will use a simple moving average (SMA) crossover strategy.

				
					# Calculate the 50-day simple moving average
sma_50 = close_df.rolling(window=50).mean()

# Calculate the 200-day simple moving average
sma_200 = close_df.rolling(window=200).mean()

# Plot the moving averages along with the historical close prices
close_df.plot(figsize=(10, 6))
sma_50.plot(linestyle='--', linewidth=1)
sma_200.plot(linestyle='--', linewidth=1)
plt.title('Moving Averages and Historical Close Prices of Popular ETFs')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend(loc='upper left')
plt.show()

				
			

Keep in mind that this is just a simple example, and more sophisticated strategies can be developed using additional indicators, machine learning algorithms, or other techniques. Always remember to backtest your strategies before implementing them in a live trading environment.

Conclusion

By using Python and the Yahoo Finance API, we have successfully downloaded historical close prices for popular ETFs, calculated daily returns, plotted price trends, and developed a simple trading strategy. This serves as a solid foundation for further exploration and analysis in the world of finance and investing.

Hire me for your next Project

I can assist you with your financial modeling and quantitative finance projects, leveraging my expertise and experience in the field.

Contact Me

Feel free to reach out to discuss your freelance project needs, and let’s collaborate on bringing your vision to life!