Python for Finance: Unleashing the Power of yfinance for Data Analysis

Amit Kumar Manjhi
Level Up Coding
Published in
4 min readMar 8, 2024

--

Photo by Maxim Hopman on Unsplash

If you’ve ever wanted to dive into the world of financial data analysis, Python’s yfinance library is a handy tool to have in your toolkit. This library allows you to easily retrieve information about stocks, including historical prices, real-time quotes, dividends, and stock splits. In this blog post, we'll explore some simple examples to get you started.

Before we jump into the examples, let’s make sure you have yfinance installed. Open your terminal or command prompt and run the following command:

pip install yfinance

1. Download Historical Stock Data

One of the most common tasks in financial analysis is fetching historical stock data. Let’s say you’re interested in Apple Inc. (AAPL) and want to see how its stock prices have changed over time. With yfinance, it's as easy as this:

import yfinance as yf

stock_symbol = "AAPL"
start_date = "2023-12-31"
end_date = "2024-03-08"

stock_data = yf.download(stock_symbol, start=start_date, end=end_date)

print(stock_data.head())
Output of the above snippet

This snippet downloads historical stock data for Apple from December 31, 2023, to March 08, 2024.

2. Real-time Stock Quotes

If you’re curious about the lowest and highest price of a stock, you can fetch real-time quotes. Here’s how you can get the lowest and highest price of Apple.

import yfinance as yf

stock_symbol = "AAPL"

stock_quote = yf.Ticker(stock_symbol)
stock_info = stock_quote.info

# Check for the availability of the 'regularMarketDayLow' and 'regularMarketDayHigh' keys
if 'regularMarketDayLow' in stock_info and 'regularMarketDayHigh' in stock_info:
low_price = stock_info['regularMarketDayLow']
high_price = stock_info['regularMarketDayHigh']
print(f"Lowest price today for {stock_symbol}: ${low_price}")
print(f"Highest price today for {stock_symbol}: ${high_price}")
else:
print(f"Price information not available for {stock_symbol}")
Lowest price today for AAPL: $168.49
Highest price today for AAPL: $170.73

Now you can keep an eye on the latest price without manually checking.

3. List of S&P 500 Companies

Want to explore the list of companies in the S&P 500 index? yfinance makes it simple:

import yfinance as yf

sp500_tickers = yf.download('^GSPC').index.values

print("S&P 500 Tickers:")
for ticker in sp500_tickers:
print(ticker)
Output of the above snippet

4. Download Dividend Data

Dividends are an essential aspect of stock investing. Let’s fetch dividend data for Apple:

import yfinance as yf

stock_symbol = "AAPL"

stock_info = yf.Ticker(stock_symbol)
dividends = stock_info.dividends

print("Dividend Data:")
print(dividends.head())

Now you can analyze when dividends were paid out.

Dividend Data:
Date
1987-05-11 00:00:00-04:00 0.000536
1987-08-10 00:00:00-04:00 0.000536
1987-11-17 00:00:00-05:00 0.000714
1988-02-12 00:00:00-05:00 0.000714
1988-05-16 00:00:00-04:00 0.000714
Name: Dividends, dtype: float64

5. Stock Splits Information

Understanding stock splits is crucial for evaluating a company’s history. Here’s how you can get stock split data:

import yfinance as yf

stock_symbol = "AAPL"

stock_info = yf.Ticker(stock_symbol)
splits = stock_info.splits

print("Stock Splits Data:")
print(splits.head())

This example retrieves information about stock splits for Apple.

Stock Splits Data:
Date
1987-06-16 00:00:00-04:00 2.0
2000-06-21 00:00:00-04:00 2.0
2005-02-28 00:00:00-05:00 2.0
2014-06-09 00:00:00-04:00 7.0
2020-08-31 00:00:00-04:00 4.0
Name: Stock Splits, dtype: float64

6. Financial data analysis

We’ll analyze the historical stock performance of two popular technology companies: Apple Inc. (AAPL) and Microsoft Corporation (MSFT). We’ll compare their stock prices and visualize the data to gain insights into their performance over time.

import yfinance as yf
import matplotlib.pyplot as plt

# Define the stock symbols
stocks = ["AAPL", "MSFT"]

# Download historical stock data
stock_data = yf.download(stocks, start="2023-01-01", end="2024-01-01")['Adj Close']

# Calculate daily returns for each stock
daily_returns = stock_data.pct_change()

# Plotting the stock prices
plt.figure(figsize=(12, 6))
for stock in stocks:
plt.plot(stock_data.index, stock_data[stock], label=stock)

plt.title('Historical Stock Prices')
plt.xlabel('Date')
plt.ylabel('Adjusted Close Price ($)')
plt.legend()
plt.show()

# Plotting the daily returns
plt.figure(figsize=(12, 6))
for stock in stocks:
plt.plot(daily_returns.index, daily_returns[stock], label=stock)

plt.title('Daily Returns')
plt.xlabel('Date')
plt.ylabel('Percentage Change')
plt.legend()
plt.show()
Output of the above snippet
Output of the above snippet

Conclusion

These examples provide a glimpse into the power of yfinance for financial data analysis. Whether you're a budding investor or a seasoned analyst, Python and yfinance make it easier to explore and understand the world of finance. Feel free to customize these examples and explore additional features offered by the library to suit your specific needs.

Happy coding!

Reference: https://pypi.org/project/yfinance/#description

--

--