Fetching Stock Data with yfinance

· 4 min read · Updated March 7, 2026 · beginner
finance stocks yfinance data beginner

In the previous guide, you set up your environment and learned the basics of financial analysis in Python. Now you will learn how to fetch real stock market data using yfinance—a free library that downloads historical prices from Yahoo Finance.

What is yfinance?

yfinance is a Python library that lets you download historical market data, fundamentals, options data, and more from Yahoo Finance. It is popular because it is free, easy to use, and covers a wide range of securities including stocks, ETFs, indices, and cryptocurrencies.

Install it with pip:

pip install yfinance

Your First Data Download

The basic workflow is simple: create a ticker object, then call methods on it to get the data you need.

import yfinance as yf

# Create a ticker for Apple
apple = yf.Ticker("AAPL")

# Download historical data
df = apple.history(period="1y")

print(df.head())

This downloads one year of daily price data for Apple. The data includes:

  • Open — the opening price
  • High — the highest price during the day
  • Low — the lowest price during the day
  • Close — the closing price
  • Volume — how many shares traded

Understanding the Data

The history method returns a pandas DataFrame with a DatetimeIndex. This makes it easy to filter by date:

import yfinance as yf
from datetime import datetime, timedelta

ticker = yf.Ticker("GOOGL")

# Get the last 6 months
six_months_ago = datetime.now() - timedelta(days=180)
df = ticker.history(start=six_months_ago)

# Filter to a specific date range
df = df[(df.index >= "2025-06-01") & (df.index <= "2025-12-31")]

print(f"Downloaded {len(df)} trading days")
print(df["Close"].describe())

Downloading Multiple Stocks

You often want to compare multiple stocks. yfinance handles this efficiently:

import yfinance as yf

# Download multiple tickers at once
tickers = yf.Tickers("AAPL GOOGL MSFT AMZN")

# Access each stock individually
for symbol in ["AAPL", "GOOGL", "MSFT", "AMZN"]:
    data = tickers.tickers[symbol].history(period="1mo")
    latest_price = data["Close"].iloc[-1]
    print(f"{symbol}: ${latest_price:.2f}")

The yf.Tickers object lets you download data for multiple symbols in a single request, which is faster than downloading them one by one.

Getting More Than Just Prices

yfinance provides access to other useful data beyond historical prices:

import yfinance as yf

ticker = yf.Ticker("NVDA")

# Get company information
info = ticker.info
print(f"Company: {info.get('longName')}")
print(f"Sector: {info.get('sector')}")
print(f"Market Cap: ${info.get('marketCap', 0):,.0f}")
print(f"P/E Ratio: {info.get('trailingPE')}")

# Get stock splits and dividends
splits = ticker.splits
dividends = ticker.dividends

print(f"\nRecent Splits:\n{splits.tail()}")
print(f"\nRecent Dividends:\n{dividends.tail()}")

This gives you fundamentals and corporate actions data—useful for fundamental analysis.

Downloading Index Data

You can also download index data using their Yahoo Finance symbols:

import yfinance as yf

# Common index symbols
indices = {
    "^GSPC": "S&P 500",
    "^DJI": "Dow Jones",
    "^IXIC": "NASDAQ"
}

for symbol, name in indices.items():
    data = yf.Ticker(symbol).history(period="5d")
    latest = data["Close"].iloc[-1]
    change = data["Close"].iloc[-1] - data["Open"].iloc[0]
    pct_change = (change / data["Open"].iloc[0]) * 100
    print(f"{name}: ${latest:,.2f} ({pct_change:+.2f}%)")

Working with Intraday Data

For shorter timeframes, you can request intraday data with different intervals:

import yfinance as yf

ticker = yf.Ticker("TSLA")

# Get 5-minute intervals for the last 7 days
intraday = ticker.history(period="5d", interval="5m")
print(intraday.tail(10))

# Get hourly data for the last month
hourly = ticker.history(period="1mo", interval="1h")
print(hourly.tail())

Available intervals include: 1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 1wk, 1mo.

Common Pitfalls

A few things to watch out for:

Wrong ticker symbols: Yahoo Finance uses specific symbols. Use “^GSPC” for S&P 500, not “SPX”. Check the symbol on finance.yahoo.com if you are unsure.

Data gaps: Weekends and holidays have no trading data. Do not expect 365 days of data for a year.

Split-adjusted prices: By default, yfinance returns split-adjusted prices. Use auto_adjust=False if you need unadjusted prices.

# Get unadjusted prices
df = ticker.history(period="1y", auto_adjust=False)

Throttling: If you make too many requests quickly, Yahoo may temporarily block you. Add small delays between requests if downloading many tickers.

When to Use yfinance

yfinance is great for:

  • Personal investing research
  • Building trading dashboards
  • Backtesting trading strategies
  • Learning financial analysis

It is not suitable for:

  • Real-time trading (data is delayed)
  • Professional trading systems (reliability guarantees)
  • High-frequency requests

Practical Example: Portfolio Overview

Let us put together a practical example that combines several concepts:

import yfinance as yf

# Define your portfolio
portfolio = {
    "AAPL": 10,   # 10 shares of Apple
    "GOOGL": 5,   # 5 shares of Google
    "MSFT": 8,    # 8 shares of Microsoft
    "AMZN": 3     # 3 shares of Amazon
}

# Download current data and calculate portfolio value
total_value = 0
print(f"{'Symbol':<8} {'Shares':<7} {'Price':<10} {'Value':<12}")
print("-" * 40)

for symbol, shares in portfolio.items():
    ticker = yf.Ticker(symbol)
    price = ticker.history(period="1d")["Close"].iloc[-1]
    value = shares * price
    total_value += value
    print(f"{symbol:<8} {shares:<7} ${price:<9.2f} ${value:<11.2f}")

print("-" * 40)
print(f"Total Portfolio Value: ${total_value:,.2f}")

This example shows how to build a simple portfolio tracker. You can expand this pattern to include historical performance, dividend income, and more complex calculations.

Summary

You now know how to:

  • Install and import yfinance
  • Download historical price data for stocks
  • Filter data by date range
  • Download multiple stocks efficiently
  • Access company fundamentals and corporate actions
  • Work with index data and intraday intervals
  • Build a simple portfolio tracker

In the next guide, you will learn how to calculate returns and volatility from this data—essential metrics for any financial analysis.