The yfinance API is a Python library that allows you to easily retrieve financial data from Yahoo Finance without manually scraping the website. It is widely used by traders, analysts, researchers, and developers for tasks like downloading historical stock prices, getting company information, and analyzing financial statements. This guide will cover everything from installation to advanced usage, with practical code examples throughout.
Introduction to yfinance
Yahoo Finance is one of the most popular sources for stock market data. It offers a broad range of data, including historical prices, real-time quotes, financial metrics, and even options data. The yfinance library acts as a convenient wrapper around Yahoo Finance, providing an intuitive Pythonic interface.
With yfinance, you can:
- Fetch historical stock, ETF, or cryptocurrency prices
- Retrieve fundamental data like revenue, earnings, and balance sheets
- Get dividends and stock split history
- Access options chain information
- Work with multiple tickers at once
Installing yfinance
You can install yfinance directly using pip:
pip install yfinance
If you are using Jupyter Notebook, prepend the command with an exclamation mark:
!pip install yfinance
It’s also a good idea to have pandas and matplotlib installed since most yfinance data is returned as Pandas DataFrames.
pip install pandas matplotlib
Importing yfinance
Once installed, you can import it into your Python code:
import yfinance as yf
import pandas as pd
This setup allows you to work with both yfinance and Pandas for analysis.
Downloading Historical Data
The most straightforward way to download data is with yf.download():
data = yf.download("AAPL", start="2022-01-01", end="2022-12-31")
print(data.head())
Common parameters:
tickers: One ticker or a list of tickersstart: Start date (YYYY-MM-DD)end: End date (YYYY-MM-DD)period: Data period (e.g.,"1mo","1y","5d")interval: Data interval (e.g.,"1d","1wk","1h","15m")auto_adjust: Adjust for splits/dividends automaticallygroup_by: Organize data by ticker if multiple are downloaded
Example with multiple tickers:
multi_data = yf.download(["AAPL", "MSFT"], start="2022-01-01", end="2022-06-01", group_by="ticker")
print(multi_data["AAPL"].head())
Using the Ticker Object
The Ticker object is yfinance’s core feature for working with a single security.
apple = yf.Ticker("AAPL")
Getting Historical Data
hist = apple.history(period="1y")
print(hist.head())
Parameters include:
period:"1d","5d","1mo","1y","max"interval:"1d","1wk","1h","15m"start/end: Custom date ranges
Getting Company Info
info = apple.info
print(info["longName"])
print(info["sector"])
This returns a dictionary with data such as:
- Name, sector, industry
- Market capitalization
- Beta, P/E ratio, EPS
- Headquarters location
Dividends and Splits
dividends = apple.dividends
splits = apple.splits
print(dividends.tail())
print(splits)
These return Pandas Series indexed by date.
Financial Statements
income_statement = apple.financials
balance_sheet = apple.balance_sheet
cash_flow = apple.cashflow
print(income_statement)
All of these return Pandas DataFrames, which are great for fundamental analysis.
Analyst Recommendations
recommendations = apple.recommendations
print(recommendations.tail())
This shows analysts’ buy/hold/sell ratings and target prices.
Options Chain
options_dates = apple.options
print(options_dates)
opt_chain = apple.option_chain(options_dates[0])
print(opt_chain.calls)
print(opt_chain.puts)
Options data is returned as two DataFrames: calls and puts.
Working with Multiple Tickers
You can loop through multiple tickers and store their data together:
tickers = ["AAPL", "MSFT", "TSLA"]
data_dict = {}
for t in tickers:
data_dict[t] = yf.Ticker(t).history(period="6mo")["Close"]
combined = pd.concat(data_dict.values(), axis=1)
combined.columns = tickers
print(combined.head())
This is useful for portfolio analysis.
Adjusted vs. Unadjusted Data
Yahoo Finance offers both raw prices and adjusted prices (accounting for splits and dividends). To automatically adjust data:
adj_data = yf.download("AAPL", period="1y", auto_adjust=True)
Adjusted data is essential for backtesting trading strategies.
Intraday Data
yfinance supports minute-level data, although historical availability is limited.
intraday = yf.download("AAPL", period="5d", interval="1h")
print(intraday.head())
For intervals like "1m" or "5m", the available history is much shorter.
Plotting with Matplotlib
Since yfinance data is a DataFrame, it integrates with Matplotlib for visualization.
import matplotlib.pyplot as plt
data = yf.download("AAPL", start="2022-01-01", end="2022-12-31")
data["Close"].plot(title="AAPL Closing Price", figsize=(10, 5))
plt.show()
You can add moving averages:
data["50_MA"] = data["Close"].rolling(window=50).mean()
data[["Close", "50_MA"]].plot(title="AAPL with 50-Day Moving Average", figsize=(10, 5))
plt.show()
Saving Data to CSV
You can easily export data for offline use:
data.to_csv("aapl_data.csv")
And later reload it:
loaded_data = pd.read_csv("aapl_data.csv", index_col=0, parse_dates=True)
Error Handling
Sometimes Yahoo Finance data may be unavailable or delayed. Use try-except blocks for safety:
try:
data = yf.download("AAPL", period="1y")
except Exception as e:
print("Error:", e)
Always check for missing values:
if data.isnull().values.any():
print("Data contains NaNs.")
Advanced Usage Examples
Fetching Cryptocurrency Data
btc = yf.Ticker("BTC-USD")
btc_hist = btc.history(period="1y")
print(btc_hist.tail())
Automating Data Updates
You can run scripts daily to keep data fresh:
latest = yf.download("AAPL", period="1d", interval="1m")
latest.to_csv("aapl_intraday.csv")
Combining yfinance with Technical Analysis
You can integrate with TA-Lib or custom indicators:
data["SMA_20"] = data["Close"].rolling(window=20).mean()
data["SMA_50"] = data["Close"].rolling(window=50).mean()
Then check for SMA crossovers to signal trades.
Conclusion
The yfinance API makes it simple to integrate financial market data into Python projects. Whether you are performing technical analysis, evaluating company fundamentals, or building automated trading systems, yfinance provides the tools you need to access accurate, up-to-date market information. By combining yfinance with Pandas for analysis and Matplotlib for visualization, you can create powerful financial analysis workflows. With just a few lines of code, you can connect Python directly to Yahoo Finance and start turning market data into insights.


