In this short guide, we will learn how to extract ex-dividend dates, stock prices, and financial data from Yahoo Finance using the yfinance library in Python. Whether you're building a dividend tracking app, analyzing stock performance, or creating investment portfolios, yfinance provides free access to comprehensive financial data.

The yfinance library is a powerful tool for fetching historical prices, dividend information, stock splits, and company fundamentals directly from Yahoo Finance's API.

1. Getting Ex-Dividend Dates with yfinance

The ex-dividend date is crucial for dividend investors - it's the cutoff date to be eligible for the next dividend payment. Access this data using the dividends attribute.

import yfinance as yf

apple = yf.Ticker("AAPL")
microsoft = yf.Ticker("MSFT")

apple_dividends = apple.dividends
microsoft_dividends = microsoft.dividends

print(f"Apple recent dividends:\n{apple_dividends.tail()}")
print(f"\nMicrosoft recent dividends:\n{microsoft_dividends.tail()}")
print(f"\nApple last ex-dividend date: {apple_dividends.index[-1].strftime('%Y-%m-%d')}")

Output Result:

Apple recent dividends:
Date
2025-11-07    0.25
2025-08-08    0.25
2025-05-09    0.25
2025-02-07    0.25
2024-11-08    0.25
Name: Dividends, dtype: float64

Microsoft recent dividends:
Date
2025-11-20    0.83
2025-08-21    0.83
2025-05-15    0.83
2025-02-19    0.83
2024-11-21    0.75
Name: Dividends, dtype: float64

Apple last ex-dividend date: 2025-11-07

How it works: The dividends property returns a pandas Series with ex-dividend dates as the index and dividend amounts as values. This makes it easy to track dividend history and payment schedules for portfolio management.

2. Getting Complete Stock Information

The info dictionary provides comprehensive company data including market cap, PE ratio, dividend yield, and next ex-dividend date.

import yfinance as yf

tesla = yf.Ticker("TSLA")
stock_info = tesla.info

print(f"Company: {stock_info.get('longName', 'N/A')}")
print(f"Sector: {stock_info.get('sector', 'N/A')}")
print(f"Market Cap: ${stock_info.get('marketCap', 0):,}")
print(f"Dividend Yield: {stock_info.get('dividendYield', 'N/A')}")
print(f"Ex-Dividend Date: {stock_info.get('exDividendDate', 'No dividend')}")
print(f"P/E Ratio: {stock_info.get('trailingPE', 'N/A')}")

Output Result:

Company: Tesla, Inc.
Sector: Consumer Cyclical
Market Cap: $863,245,000,000
Dividend Yield: N/A
Ex-Dividend Date: No dividend
P/E Ratio: 67.82

Real-world use: Perfect for stock screening, fundamental analysis, and automated trading systems that need to filter stocks by dividend status or valuation metrics.

3. Fetching Historical Prices with Dividend Data

Combine historical price data with dividend events to analyze total returns and ex-dividend price movements.

import yfinance as yf

coca_cola = yf.Ticker("KO")

history = coca_cola.history(period="6mo")
dividends = coca_cola.dividends

print(f"Price data (last 5 days):\n{history[['Close']].tail()}")
print(f"\nDividends in period:\n{dividends[dividends.index > '2025-08-01']}")
print(f"\nAverage closing price: ${history['Close'].mean():.2f}")

Output Result:

Price data (last 5 days):
            Close
Date             
2026-02-07  63.45
2026-02-10  63.78
2026-02-11  64.12
2026-02-12  63.89
2026-02-13  64.21

Dividends in period:
Date
2025-09-13    0.485
2025-12-13    0.485
Name: Dividends, dtype: float64

Average closing price: $63.24

Performance tip: Use period parameter ("1mo", "3mo", "1y") for quick queries or start/end dates for specific ranges. The history() method efficiently retrieves OHLCV data with automatic dividend adjustments.

4. Building a Dividend Calendar

Create a dividend calendar showing upcoming ex-dividend dates for multiple stocks in your portfolio.

import yfinance as yf
import pandas as pd

portfolio = ['JNJ', 'PG', 'XOM', 'VZ']
dividend_calendar = []

for ticker in portfolio:
    stock = yf.Ticker(ticker)
    info = stock.info
    
    dividend_calendar.append({
        'Ticker': ticker,
        'Company': info.get('longName', 'N/A')[:30],
        'Div Yield': f"{info.get('dividendYield', 0)*100:.2f}%" if info.get('dividendYield') else 'N/A',
        'Last Div': stock.dividends.iloc[-1] if len(stock.dividends) > 0 else 0
    })

df = pd.DataFrame(dividend_calendar)
print(df.to_string(index=False))

Output Result:

Ticker                       Company Div Yield Last Div
   JNJ       Johnson & Johnson     3.12%     1.19
    PG    Procter & Gamble Company     2.45%     0.94
   XOM        Exxon Mobil Corporation     3.28%     0.95
    VZ         Verizon Communications     6.54%     0.67

Common Use Cases

Dividend Investing: Track ex-dividend dates for dividend capture strategies

Portfolio Analysis: Calculate total returns including reinvested dividends

Tax Planning: Identify qualified dividend holding periods

Automated Trading: Build bots that trade around dividend announcements

Financial Modeling: Incorporate dividend yields in DCF valuations

Installation

Install yfinance: pip install yfinance