yfinance: 10 Ways to Get Stock Data with Python
The yfinance
library offers Python users a seamless way to retrieve stock data from Yahoo Finance. Whether you're a beginner or a seasoned analyst, this library provides a range of functionalities to help you gather and analyze stock information. In this blog post, we will delve into 10 fundamental ways to retrieve stock data using yfinance
.
1. Fetching Historical Data
The download
method is your go-to for obtaining historical data for any stock.
import yfinance as yf
data = yf.download("AAPL", start="2020-01-01", end="2021-01-01")
print(data.head())
2. Ticker Object
The Ticker
class allows you to access various data for a specific stock.
apple = yf.Ticker("AAPL")
print(apple.info) # General information about Apple Inc.
3. Getting Recent Data
Want data for the most recent trading days? Here’s how:
recent_data = yf.download("AAPL", period="5d")
print(recent_data)
4. Fetching Data for Multiple Tickers
Retrieve data for multiple stocks in one go.
multi_data = yf.download(["AAPL", "MSFT"], start="2020-01-01", end="2021-01-01")
print(multi_data)
5. Adjusted Data Retrieval
Obtain adjusted data, which accounts for stock splits, dividends, etc.
data = yf.download("AAPL", start="2020-01-01", end="2021-01-01", auto_adjust=True)
print(data['Close']) # This will show the adjusted close prices
6. Interval-based Data Retrieval
Retrieve data based on specific intervals, like daily or weekly.
weekly_data = yf.download("AAPL", start="2020-01-01", end="2021-01-01", interval="1wk")
print(weekly_data)
7. Retrieving Dividends and Splits
Access dividend and stock split history.
apple = yf.Ticker("AAPL")
dividends = apple.dividends
splits = apple.splits
print(dividends, splits)
8. Real-time Data
Fetch the most up-to-date stock price.
apple = yf.Ticker("AAPL")
print(apple.history(period="1d"))
9. Data for Specific Dates
Obtain data for a specific date range.
data = yf.download("AAPL", start="2022-01-01", end="2022-12-31")
print(data)
10. Visualization with yfinance
Visualize historical data with ease.
import matplotlib.pyplot as plt
data = yf.download("AAPL", start="2020-01-01", end="2021-01-01")
data['Close'].plot()
plt.title("Apple Stock Prices")
plt.show()