The yfinance
module is a Python library used to fetch historical market data from Yahoo Finance. It provides an easy way to access financial data such as stock prices, historical data, and other financial metrics. The module is particularly useful for data analysis, algorithmic trading, and financial research.
1. Installation
To use the yfinance
module, you need to install it via pip:
pip install yfinance
2. Basic Usage
The yfinance
module provides functions to download financial data and access various stock information. Here’s how to use it for basic tasks:
2.1 Fetching Historical Data
You can fetch historical stock data using the yf.download()
function:
import yfinance as yf
# Download historical data for a stock
data = yf.download('AAPL', start='2023-01-01', end='2024-01-01')
# Print the data
print(data.head())
This code downloads historical data for Apple Inc. (AAPL) between January 1, 2023, and January 1, 2024. The data includes Open, High, Low, Close, Volume, and Adjusted Close prices.
2.2 Fetching Stock Info
To get detailed information about a stock, use the yf.Ticker()
class:
import yfinance as yf
# Create a Ticker object for a stock
ticker = yf.Ticker('AAPL')
# Fetch stock information
info = ticker.info
print(info)
This code retrieves and prints detailed information about Apple Inc., including market capitalization, P/E ratio, and more.
2.3 Fetching Financials and Balances
You can also fetch financial statements such as income statements and balance sheets:
import yfinance as yf
# Create a Ticker object
ticker = yf.Ticker('AAPL')
# Fetch financial statements
financials = ticker.financials
balance_sheet = ticker.balance_sheet
print(financials.head())
print(balance_sheet.head())
This code retrieves and prints the financial statements and balance sheet for Apple Inc.
3. Working with Data
The data fetched using yfinance
is typically returned as a Pandas DataFrame, which allows for powerful data manipulation and analysis. You can use Pandas functions to analyze and visualize the data:
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
# Download historical data
data = yf.download('AAPL', start='2023-01-01', end='2024-01-01')
# Calculate moving average
data['SMA_50'] = data['Close'].rolling(window=50).mean()
# Plot data
plt.figure(figsize=(10, 5))
plt.plot(data['Close'], label='Close Price')
plt.plot(data['SMA_50'], label='50-Day SMA', linestyle='--')
plt.title('Apple Inc. Stock Price and 50-Day SMA')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.show()
This example calculates a 50-day simple moving average (SMA) for Apple Inc. and plots both the closing price and the SMA.
4. Advanced Usage
For more advanced usage, yfinance
also supports fetching data for multiple tickers, setting custom intervals, and more:
import yfinance as yf
# Download data for multiple tickers
data = yf.download(['AAPL', 'MSFT'], start='2023-01-01', end='2024-01-01')
# Print the data
print(data.head())
This code downloads historical data for both Apple Inc. and Microsoft Corporation.
5. Conclusion
The yfinance
module is a powerful tool for accessing and analyzing financial data from Yahoo Finance. With its easy-to-use interface and support for various types of financial data, it is well-suited for tasks ranging from simple data retrieval to complex financial analysis and modeling.