yfinance is a Python library designed to simplify access to Yahoo Finance data.
Originally, Yahoo Finance had its own official API, but after discontinuing it in 2017, many developers searched for alternatives. In response, Ran Aroussi created yfinance
(initially named fix-yahoo-finance
) to make retrieving stock prices, currency rates, and financial data easier through web scraping.
At first, it was used informally, but as its popularity grew, it became widely adopted in stock analysis, algorithmic trading, and quantitative investing. Today, it remains an actively maintained open-source project, receiving continuous updates.
I’ve put together a simple data collection example using yfinance
. Since stocks attract a lot of attention, there’s plenty of similar code available, whether for stocks, funds, or financial analysis. Let’s start by collecting data and then explore how to use it effectively.
Also, it’s been a while since I last heard the name Yahoo, but no doubt, it’s a company with a long history!
Get a Ticker object for a given instrument
def get_stock_data_ticker(target):
_msft = yf.Ticker(target)
return _msft
Download price data for a given stock
def get_stock_data_download(target):
_aapl = yf.download(target)
return _aapl
Get fund data
def get_funds_data_ticker(target):
_spy = yf.Ticker(target).funds_data
return _spy
yfinance Output
if "__main__" == __name__:
msft = get_stock_data_ticker("MSFT")
print(msft.info)
print(msft.calendar)
print(msft.analyst_price_targets)
print(msft.quarterly_income_stmt)
print(msft.history(period='1mo'))
print(msft.option_chain(msft.options[0]).calls)
aapl = get_stock_data_download('AAPL')
print(aapl.head())
spy = get_funds_data_ticker('SPY')
print(spy.description)
print(spy.top_holdings)
- msft.info: General information about Microsoft (company overview, market capitalization, industry, etc.)
- msft.calendar: Calendar of earnings announcements and key events
- msft.analyst_price_targets: Price target information from brokerage firm analysts
- msft.quarterly_income_stmt: Quarterly income statements
- msft.history(period=’1mo’): Stock price data (OHLC, volume) for the past month
- msft.option_chain(msft.options[0]).calls: call option data for the latest expiration date
- Using head() to output the top 5 data.
- spy.description: Description of SPY fund
- spy.top_holdings: information about SPY’s top holdings
Site
https://github.com/zafrem/Learn-Code/tree/main/Python-Class/01_Data_collector/1_Collector
Code
pip Package
pip install yfinance
pip package yfinance
https://pypi.org/project/yfinance