What is yfinance?

In the Python ecosystem, one of the easiest ways to retrieve financial data is through yfinance, a popular open-source library for yfinance in Python. It allows developers and data analysts to access stock prices, ETFs, financial statements, and options data from Yahoo Finance with just a few lines of code.

Yahoo once offered its own official API, but it was discontinued in 2017. This led many developers to seek alternatives. To fill this gap, developer Ran Aroussi created a tool initially known as fix-yahoo-finance, which later evolved into yfinance in Python.

As of 2025, yfinance remains a go-to solution for stock market data, widely used in quantitative trading, algorithmic investing, and educational projects around financial analysis.

This tutorial will help you get started with yfinance in Python so you can effectively analyze stock and ETF data.

yfinance in Python

How to Install yfinance

Installing yfinance is straightforward using pip:

pip install yfinance

You can also find it on PyPI:
https://pypi.org/project/yfinance


Basic Usage: Retrieving Data with the Ticker Object

Fetching Stock Data with Ticker

Using the Ticker object, you can easily retrieve detailed information about a given stock. Here’s how to access Microsoft’s data using its ticker symbol:

import yfinance as yf

def get_stock_data_ticker(target):
    ticker = yf.Ticker(target)
    return ticker

msft = get_stock_data_ticker("MSFT")

print(msft.info)                        # Basic company info
print(msft.calendar)                   # Earnings calendar
print(msft.analyst_price_targets)      # Analyst price targets
print(msft.quarterly_income_stmt)      # Quarterly income statement
print(msft.history(period='1mo'))      # One-month price history
print(msft.option_chain(msft.options[0]).calls)  # Call options data

Explanation of Key Outputs

  • info: General details (industry, market cap, CEO, etc.)
  • calendar: Key events and earnings release dates
  • analyst_price_targets: Forecasts from financial analysts
  • quarterly_income_stmt: Quarterly earnings report
  • history: Historical OHLC price and volume data
  • option_chain: Options chain for the nearest expiration date

Downloading Historical Price Data

If your primary interest is historical price data for analysis, use the download() function:

def get_stock_data_download(target):
    data = yf.download(target)
    return data

aapl = get_stock_data_download("AAPL")
print(aapl.head())

This returns a pandas.DataFrame and is ideal for technical analysis or price trend visualization.


Retrieving ETF and Fund Data

You can also pull ETF or mutual fund data using yfinance in the same way:

def get_funds_data_ticker(target):
    fund = yf.Ticker(target)
    return fund

spy = get_funds_data_ticker("SPY")

print(spy.info['longBusinessSummary'])  # Fund description
print(spy.fund_holdings)                # Top fund holdings

As of 2025, SPY (S&P 500 ETF) remains one of the most actively traded ETFs worldwide, and having access to its holdings is particularly useful for building index-based strategies.


Practical Example: Looping Through Multiple Stocks

stocks = ['MSFT', 'AAPL', 'GOOGL', 'TSLA']
for symbol in stocks:
    ticker = yf.Ticker(symbol)
    info = ticker.info
    print(f"{symbol}: {info.get('shortName')} - Market Cap: {info.get('marketCap')}")

This code snippet loops through multiple tickers and prints the basic information, making it suitable for automated stock screening scripts.


Real-World Applications of yfinance in Python

1. Technical Analysis

Use historical price data to compute moving averages, RSI, MACD, and other trading indicators.

2. Algorithmic Trading

While yfinance doesn’t support real-time streaming, it’s an excellent choice for backtesting trading strategies using historical data.

3. Fundamental Analysis

Financial statements such as income statements, balance sheets, and cash flow statements are available for analyzing company fundamentals.

4. ETF Portfolio Analysis

By accessing ETF holdings data, you can monitor portfolio compositions and understand broader market exposure.


Limitations of yfinance

Despite its usefulness, yfinance in Python does have some limitations:

  • Not real-time: Data may be slightly delayed and is not suitable for high-frequency trading.
  • Web scraping based: Changes in Yahoo Finance’s website layout can break functionality.
  • Unofficial API: It is not endorsed by Yahoo, so long-term support is uncertain.

Final Thoughts: Is yfinance Still Relevant in 2025?

Absolutely.

In 2025, yfinance continues to be one of the most accessible and powerful tools for stock and ETF data collection. Whether you’re building your first financial dashboard or running algorithmic trading strategies, this library offers both simplicity and flexibility.

It’s open-source, community-supported, and integrates easily with other Python tools like pandas, matplotlib, and scikit-learn.


GitHub Resources

By Mark

-_-

Leave a Reply

Your email address will not be published. Required fields are marked *