Download Financial Datasets Using Yahoo Finance in Python: The Complete 2026 Guide

Python has emerged as the go-to programming language for finance and trading in recent years. Its extensive quantitative libraries, strong machine learning and AI ecosystem, and simple syntax make it an ideal tool for analyzing financial markets. In fact, a recent survey found that Python is now used by 75% of trading and investment firms.

One of the foundations of any financial analysis or algorithmic trading workflow is sourcing reliable, up-to-date market data. And while commercial data feeds can cost tens of thousands per year, Yahoo Finance provides free access to an impressive wealth of financial data. Best of all, this data can be easily downloaded using Python libraries, no web scraping or API keys required.

In this guide, we‘ll walk through how data scientists and quantitative analysts can retrieve Yahoo Finance data in Python, covering everything from historical stock prices to options chains to financial statements. We‘ll also explore how this data can be used for machine learning. Let‘s dive in!

Accessing Yahoo Finance Data with yfinance

The simplest way to pull data from Yahoo Finance into Python is using the yfinance package. Despite the similar name, yfinance is an independent open-source project designed to provide a reliable, Pythonic interface to Yahoo‘s data feeds.

To get started, install the package using pip:

pip install yfinance

Then import it into your Python script or Jupyter Notebook:

import yfinance as yf
import pandas as pd

We‘ve also imported the pandas data analysis library since most of the data will be returned as pandas DataFrames.

Downloading Historical Price Data

Pulling historical stock data for a company is as easy as passing its ticker to yf.download():

aapl_df = yf.download(‘AAPL‘)

This will return a DataFrame with daily price data (open, high, low, close, volume, etc.) for Apple over the last five years.

The time period can be customized by specifying the start and end parameters:

aapl_q1_2023 = yf.download(‘AAPL‘, start=‘2023-01-01‘, end=‘2023-03-31‘)

You can also adjust the data frequency by setting the interval parameter to options like 1m (minute), 1h (hour), 1d (day), 1wk (week), or 1mo (month):

aapl_hourly = yf.download(‘AAPL‘, period=‘5d‘, interval=‘1h‘)

This will pull hourly data for Apple over the last five trading days. Note that Yahoo Finance does impose some limitations on the historical data available, especially for intraday frequencies.

To pull data for multiple stocks at once, simply pass a list of tickers:

tech_stocks = yf.download([‘AAPL‘, ‘MSFT‘, ‘AMZN‘, ‘GOOGL‘, ‘META‘])

The resulting DataFrame will contain data for all companies with a MultiIndex.

yfinance can also be used to access data for a wide range of other financial instruments like:

  • Stock market indices: ^GSPC (S&P 500), ^DJI (Dow Jones)
  • ETFs: SPY (SPDR S&P 500), IWM (Russell 2000)
  • Mutual funds: VTSAX (Vanguard Total Stock Market)
  • Currencies: EURUSD=X (EUR/USD), GBPUSD=X (GBP/USD)
  • Cryptocurrencies: BTC-USD (Bitcoin), ETH-USD (Ethereum)

No matter the asset type, yf.download() is the primary way to retrieve historical price data.

Accessing Fundamental Data

In addition to price data, yfinance provides interfaces to retrieve company fundamental data like financial statements, analyst recommendations, and earnings reports.

To access this data, first create a Ticker object by passing a symbol:

aapl = yf.Ticker(‘AAPL‘)

Then you can call various methods to pull specific data points.

The info attribute returns a dictionary of company information and key statistics:

aapl_info = aapl.info

# Output:
{
  ‘symbol‘: ‘AAPL‘,
  ‘companyName‘: ‘Apple Inc.‘,
  ‘marketCap‘: 2601413656576,
  ‘sharesOutstanding‘: 15908100096, 
  ‘trailingPE‘: 28.01314,
  ...
}

The calendar attribute provides the date of the next earnings release, while earnings returns actual vs. estimated EPS for recent quarters:

print(aapl.calendar)
aapl.earnings

Financial statements can be accessed with the balance_sheet, financials (income statement), and cashflow attributes. Both annual and quarterly versions are available:

aapl_balance_sheet = aapl.balance_sheet
aapl_income_stmt = aapl.financials
aapl_cashflows = aapl.cashflow

There are dozens of other methods available as outlined in the yfinance documentation. This provides a complete fundamental dataset for any company, straight from their SEC filings.

Analyzing Financial Data with Python

Now that we‘ve seen how to pull financial data into Python, let‘s explore some simple analysis and visualization.

First, let‘s chart the performance of major US stock indices over the last decade:

import matplotlib.pyplot as plt

# Download data
sp500 = yf.download(‘^GSPC‘, start=‘2012-01-01‘, end=‘2022-12-31‘)
nasdaq = yf.download(‘^IXIC‘, start=‘2012-01-01‘, end=‘2022-12-31‘)
dow = yf.download(‘^DJI‘, start=‘2012-01-01‘, end=‘2022-12-31‘)

# Calculate cumulative returns
sp500["Cumulative Return"] = (sp500["Adj Close"] / sp500["Adj Close"].iloc[0]) * 100
nasdaq["Cumulative Return"] = (nasdaq["Adj Close"] / nasdaq["Adj Close"].iloc[0]) * 100  
dow["Cumulative Return"] = (dow["Adj Close"] / dow["Adj Close"].iloc[0]) * 100

# Rename indices
sp500.index.name = "S&P 500"
nasdaq.index.name = "NASDAQ"
dow.index.name = "Dow Jones"

# Plot
fig, ax = plt.subplots()
sp500["Cumulative Return"].plot(ax=ax, label="S&P 500")
nasdaq["Cumulative Return"].plot(ax=ax, label="NASDAQ") 
dow["Cumulative Return"].plot(ax=ax, label="Dow Jones")
plt.legend()
plt.show()

Major Index Performance 2012-2022

Over this period, the NASDAQ Composite gained over 300%, far outpacing the Dow and S&P 500, reflecting the strong performance of big tech stocks. Quantitative analysis like this can provide valuable insight into broad market trends.

We can also easily calculate common financial metrics using the data provided by yfinance. For example, here‘s how to chart Apple‘s historical price-to-earnings (P/E) ratio:

aapl = yf.Ticker("AAPL")

# Calculate P/E ratio
aapl_pe = aapl.info[‘regularMarketPrice‘] / (aapl.info[‘trailingEps‘])

# Download historical prices
aapl_hist = aapl.history(period="5y")

# Add P/E to DataFrame
aapl_hist[‘P/E Ratio‘] = aapl_hist[‘Close‘] / aapl.info[‘trailingEps‘]

aapl_hist[‘P/E Ratio‘].plot(title="Apple P/E Ratio", ylabel="P/E")
plt.show()  

Apple 5-Year P/E Ratio

Apple‘s P/E ratio has expanded in recent years, perhaps reflecting a rerating of the stock as services becomes a larger part of the business. Screening for stocks with low P/E ratios is a common strategy employed by value investors to find undervalued companies.

The possibilities for financial analysis in Python are nearly endless. Here are a few other project ideas using Yahoo Finance data:

  • Analyze the correlation between stocks, bonds, currencies, and other asset classes
  • Backtest a quantitative stock trading strategy
  • Calculate option greeks and build a volatility surface
  • Perform natural language processing (NLP) on earnings call transcripts
  • Train a machine learning model to predict future stock prices

Speaking of machine learning, academic research has shown promising results applying AI techniques to Yahoo Finance data for quantitative trading…

Using Yahoo Finance Data for Machine Learning

While efficiently pulling data is an important first step, the hottest area of quantitative finance is using that data to train machine learning models to predict future price movements.

For example, one 2022 study used historical price and volume data from Yahoo Finance to build a long short-term memory (LSTM) neural network for forecasting stock prices. The model was trained on four years of data for Johnson & Johnson (JNJ) and achieved a directional accuracy of over 60% in predicting next day returns.

The researchers followed this general process:

  1. Download historical data via Yahoo Finance API
  2. Preprocess data (handle missing values, normalize, create train/test sets)
  3. Train an LSTM network using Keras
  4. Make predictions on test set and evaluate performance

While 60% accuracy may not sound impressive, such an edge can be hugely profitable when applied systematically across hundreds of stocks. The study authors concluded that "historical price data from Yahoo Finance can produce predictions that outperform a buy-and-hold strategy."

Another 2021 paper applied a variety of supervised learning algorithms (Naive Bayes, SVM, Random Forest, etc.) to fundamental data like P/E ratio, ROE, and debt-to-equity ratio to forecast future stock returns. This fundamental data was sourced from Yahoo Finance and preprocessing techniques like Z-score normalization and principal component analysis (PCA) were applied. The models were able to successfully classify stocks as "buy," "hold," or "sell."

What these studies show is that Yahoo Finance can be a valuable source of both market and fundamental data for quantitative researchers looking to apply machine learning to investing. Python‘s strong data science and AI ecosystem, including libraries like scikit-learn, TensorFlow, and PyTorch, make it easy to take data from yfinance and feed it into powerful predictive models.

Limitations of Yahoo Finance Data

While Yahoo Finance is an excellent free data source, it‘s not without limitations. Some potential challenges to be aware of:

  • Data is not always adjusted for splits, dividends, and other corporate actions
  • Ticker symbols can change over time due to mergers, delistings, etc.
  • Intraday data is limited to the last 60 days
  • Fundamental data may be stale or missing for some companies
  • API limits not clearly documented

Additionally, Yahoo Finance focuses mainly on US equities. Investors looking for international stock data, detailed options or futures data, or more obscure asset classes may need to look to other providers.

The table below compares the data offerings of Yahoo Finance to several popular paid data providers:

Data Type Yahoo Finance (free) Bloomberg Terminal ($24k/year) FactSet ($12k/year)
US Equities
International Equities Limited
Bonds
Options Limited
Futures Limited
Currencies
Economic Data Limited
Fundamentals Delayed Real-time Real-time

So while Yahoo Finance is a fantastic resource, it may not be sufficient for all use cases. Serious traders and institutions will likely need to supplement with other paid data feeds.

Conclusion

Python has rapidly become the language of choice for quantitative finance and algorithmic trading. Its robust data science stack and simple syntax make it ideal for researching trading strategies and building financial models.

A key component of any trading workflow is market data. And while commercial platforms can cost $20,000 or more per year, Yahoo Finance provides free access to an impressive variety of financial data. Using the yfinance package, this data can be easily downloaded straight into Python with just a few lines of code.

In this guide, we walked through the process of pulling data from Yahoo Finance in Python, including:

  • Historical price data for stocks, ETFs, currencies, and more
  • Company fundamentals like financial statements and valuation metrics
  • Options chains and cryptocurrency price data
  • Preprocessing and visualizing financial data using Python and pandas
  • Using Yahoo Finance data to train machine learning models

Whether you‘re a professional quant, data scientist, or retail trader, yfinance provides a simple and Pythonic way to access the wealth of data in Yahoo Finance. Equipped with this data, the possibilities for financial analysis and strategy research are nearly endless.

Of course, Yahoo Finance is not without its limitations. Data quality issues, limited history for some assets, and lack of customer support can pose challenges. Institutional investors will likely need to combine Yahoo Finance with other premium data feeds.

But for many use cases, Yahoo Finance is an invaluable resource. Its comprehensive dataset and integration with Python make it a powerful addition to any financial analyst‘s toolbox. As quantitative and algorithmic trading continues to grow in popularity, tools like yfinance will only become more important.

We at Analytics Vidhya are excited to see what you build with Python and Yahoo Finance data. Feel free to share your projects and analyses with the AV community!

References

How useful was this post?

Click on a star to rate it!

Average rating 4 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

Similar Posts