How To Use yfinance API With Python

The yfinance API is a Python package that allows you to retrieve financial data directly from Yahoo Finance. It’s an excellent tool for analysts, traders, data scientists, and hobbyists who need market data for research, backtesting, or building trading systems. By using yfinance, you can quickly pull historical price data, financial statements, dividends, stock splits, and much more—all with straightforward Python commands.

Forex Robotron

Introduction to yfinance

Yahoo Finance has been a widely used source for financial data for years, offering both historical and real-time information on stocks, ETFs, mutual funds, indices, and cryptocurrencies. The yfinance Python library wraps the Yahoo Finance API endpoints and delivers the data in a Pandas DataFrame format for easy analysis.

Forex Robotron

With yfinance, you can:

  • Download daily, weekly, monthly, or intraday market data
  • Retrieve dividends and split history
  • Access company metadata and financial statements
  • Fetch analyst recommendations and options data
  • Work with multiple tickers in one request

Installing yfinance

You can install yfinance with pip:

pip install yfinance

In a Jupyter Notebook environment:

!pip install yfinance

It’s recommended to also have pandas and matplotlib installed for data manipulation and visualization:

pip install pandas matplotlib

Importing the Library

Once installed, import the library into your Python script or notebook:

import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt

This setup prepares you for downloading, analyzing, and visualizing financial data.

Downloading Historical Price Data

The simplest way to get historical data is to use the download() function:

data = yf.download("AAPL", start="2022-01-01", end="2022-12-31")
print(data.head())

Parameters:

  • tickers: Ticker symbol(s), e.g., "AAPL" or ["AAPL", "MSFT"]
  • start / end: Date range
  • period: Alternative to start/end, e.g., "1d", "1y", "max"
  • interval: Data frequency, e.g., "1d", "1wk", "1h"
  • auto_adjust: Adjust for dividends and splits automatically
  • group_by: "ticker" to group data for multiple tickers

Example with multiple tickers:

multi_data = yf.download(["AAPL", "MSFT"], start="2022-01-01", end="2022-06-30", group_by="ticker")

Using the Ticker Object

The Ticker object lets you access all available information for a single security.

apple = yf.Ticker("AAPL")

Historical Data

hist = apple.history(period="1y", interval="1d")
print(hist.tail())

You can specify start and end dates instead of period.

Company Information

info = apple.info
print(info["longName"])
print(info["sector"])

This dictionary includes:

  • Sector and industry
  • Market cap
  • P/E ratio
  • Company description
  • Headquarters location

Dividends and Splits

dividends = apple.dividends
splits = apple.splits

Both are Pandas Series indexed by date.

Financial Statements

income_statement = apple.financials
balance_sheet = apple.balance_sheet
cash_flow = apple.cashflow

These return DataFrames suitable for further analysis.

Analyst Recommendations

recommendations = apple.recommendations

Gives a history of analyst ratings and price targets.

Options Data

options_dates = apple.options
print(options_dates)
opt_chain = apple.option_chain(options_dates[0])
print(opt_chain.calls)
print(opt_chain.puts)

This retrieves calls and puts for a specific expiration date.

Adjusted vs. Unadjusted Prices

If you want prices adjusted for dividends and stock splits:

adj_data = yf.download("AAPL", period="1y", auto_adjust=True)

This produces a consistent price series for backtesting.

Intraday Data

You can retrieve shorter interval data for recent trading days:

intraday = yf.download("AAPL", period="5d", interval="30m")
print(intraday.head())

Note: Intraday data availability is limited.

Working with Multiple Tickers

To download data for a portfolio:

tickers = ["AAPL", "MSFT", "TSLA"]
portfolio_data = yf.download(tickers, period="6mo", group_by="ticker")

Or to merge just closing prices:

close_prices = pd.DataFrame()
for t in tickers:
    close_prices[t] = yf.Ticker(t).history(period="6mo")["Close"]
print(close_prices.head())

Plotting Price Data

Visualizing data is straightforward with Matplotlib:

data = yf.download("AAPL", start="2022-01-01", end="2022-12-31")
data["Close"].plot(title="AAPL Closing Price", figsize=(10,5))
plt.show()

Adding a moving average:

data["50_MA"] = data["Close"].rolling(window=50).mean()
data[["Close", "50_MA"]].plot(title="AAPL Price with 50-Day Moving Average", figsize=(10,5))
plt.show()

Saving Data

Export to CSV for future use:

data.to_csv("aapl_data.csv")

Reload later:

loaded = pd.read_csv("aapl_data.csv", index_col=0, parse_dates=True)

Error Handling

It’s important to handle exceptions in production scripts:

try:
    data = yf.download("AAPL", period="1y")
except Exception as e:
    print("Error fetching data:", e)

Check for missing data:

if data.isnull().values.any():
    print("Warning: Missing values found.")

Advanced Usage

Cryptocurrency Data

btc = yf.Ticker("BTC-USD")
btc_hist = btc.history(period="1y")
print(btc_hist.tail())

Scheduling Updates

Use task schedulers like cron (Linux/Mac) or Task Scheduler (Windows) to update CSV files daily.

latest_data = yf.download("AAPL", period="1d", interval="1m")
latest_data.to_csv("aapl_intraday.csv")

Combining with Technical Indicators

data["SMA20"] = data["Close"].rolling(window=20).mean()
data["SMA50"] = data["Close"].rolling(window=50).mean()

These can be used to identify crossover trading signals.

Conclusion

The yfinance API is a powerful tool for integrating Yahoo Finance data into Python projects. Whether you’re building investment dashboards, conducting market research, or backtesting trading strategies, yfinance provides an accessible and efficient way to obtain the data you need. Combined with Pandas for analysis and Matplotlib for visualization, it can form the foundation of a complete market analysis workflow, allowing you to move from raw data to actionable insights with ease.

Forex Robotron
Investing Robots
Investing Robots

We review and rate forex robots, stock trading robots and crypto robots. Our team have many years of experience testing thousands of trading robots so that we can provide readers with feedback based on our own opinions.

InvestingRobots.com
Logo