Introduction to Yahoo Finance API in Python
- Yahoo Finance offers a comprehensive API known as `yfinance` that allows users to programmatically interact with market data directly within Python scripts.
- The `yfinance` library is an easy-to-use Python wrapper for downloading practically all types of data available on Yahoo Finance.
pip install yfinance
Downloading Historical Data
- To retrieve historical stock market data, you'll primarily interact with the `Ticker` class in `yfinance`.
- To get historical data, first import yfinance and create a Ticker object with the appropriate stock symbol.
import yfinance as yf
# Define the ticker symbol
tickerSymbol = 'AAPL'
# Get data on this ticker
tickerData = yf.Ticker(tickerSymbol)
# Get historical prices for this ticker
tickerDf = tickerData.history(period='1d', start='2020-1-1', end='2023-1-1')
print(tickerDf)
Fetching Live Stock Data
- The `yfinance` module also makes it easy to retrieve real-time stock data directly into your Python environment.
- For example, you can extract current price and volume information effortlessly.
# Get the current stock price
currentPrice = tickerData.history(period='1d')['Close'][0]
print(f'Current Price: {currentPrice}')
Downloading Multiple Stocks
- `yfinance` allows the downloading of information about multiple stocks simultaneously. This can be done through a loop or using the `YahooFinancials` class from another package like `yahoo_fin`.
- Next example demonstrates how to load multiple tickers at once.
# Define the ticker symbols
tickerSymbols = ['AAPL', 'MSFT', 'GOOGL']
# Use yfinance's download method to get data for multiple stocks
tickerData = yf.download(tickerSymbols, start='2020-1-1', end='2023-1-1')
print(tickerData['Adj Close'])
Interpreting Data
- The dataframe returned by `yfinance` typically includes data fields like Open, High, Low, Close, Volume, and Dividends. Each of these offers insights into stock performance over the given time period.
# Display the first few rows of the dataset
print(tickerDf.head())
# Access more detailed information on the stock
info = tickerData.info
print(info)
Efficient Data Retrieval
- To avoid requesting redundant data from the Yahoo server, store any needed information locally and ensure that your queries are as specific as possible by narrowing down your filters.
# Save dataframe to CSV for local caching
tickerDf.to_csv('aapl_stock_data.csv')
Additional Features of yfinance
- `yfinance` can also be used to extract options data, fetch sustainability scores, or even access analysts' recommendations.
- Explore the official `yfinance` documentation to utilize any of these additional features to their fullest extent.
# Get options expiration dates
options_expiration_dates = tickerData.options
print(options_expiration_dates)
# Fetch news related to the ticker
news = tickerData.news
print(news)