Convert Figma logo to code with AI

ranaroussi logoyfinance

Download market data from Yahoo! Finance's API

12,935
2,294
12,935
182

Top Related Projects

Extract data from a wide range of Internet sources into a pandas DataFrame.

2,109

Common financial technical indicators implemented in Pandas.

Python module to get stock data from Yahoo! Finance

Real time stock and option data.

A python wrapper for Alpha Vantage API for financial data.

17,485

Zipline, a Pythonic Algorithmic Trading Library

Quick Overview

yfinance is a popular Python library that provides a simple and efficient way to download historical market data from Yahoo Finance. It offers a reliable alternative to the deprecated Yahoo Finance API, allowing users to fetch stock quotes, financial statements, and other market data for analysis and research purposes.

Pros

  • Easy to use with a straightforward API
  • Provides access to a wide range of financial data, including stock prices, dividends, and company information
  • Supports downloading data for multiple symbols simultaneously
  • Regularly maintained and updated by the community

Cons

  • Relies on web scraping, which may be affected by changes to Yahoo Finance's website structure
  • Data accuracy and availability can sometimes be inconsistent
  • Limited historical data compared to paid financial data providers
  • May experience rate limiting or temporary blocks from Yahoo Finance

Code Examples

Fetching historical stock data:

import yfinance as yf

# Download historical data for AAPL
aapl = yf.Ticker("AAPL")
hist = aapl.history(period="1mo")
print(hist)

Getting company information:

import yfinance as yf

# Get company information for Tesla
tesla = yf.Ticker("TSLA")
info = tesla.info
print(f"Company Name: {info['longName']}")
print(f"Market Cap: ${info['marketCap']:,}")

Downloading data for multiple symbols:

import yfinance as yf

# Download data for multiple symbols
data = yf.download(["AAPL", "MSFT", "GOOG"], start="2022-01-01", end="2023-01-01")
print(data.head())

Getting Started

To get started with yfinance, follow these steps:

  1. Install the library using pip:

    pip install yfinance
    
  2. Import the library in your Python script:

    import yfinance as yf
    
  3. Use the Ticker object to fetch data for a specific stock:

    ticker = yf.Ticker("AAPL")
    history = ticker.history(period="1mo")
    print(history)
    

That's it! You can now start exploring the various features and data available through yfinance.

Competitor Comparisons

Extract data from a wide range of Internet sources into a pandas DataFrame.

Pros of pandas-datareader

  • Supports multiple data sources beyond Yahoo Finance
  • Integrated with the pandas ecosystem
  • More stable and consistent API

Cons of pandas-datareader

  • Less frequent updates and maintenance
  • Limited to daily data for most sources
  • Slower data retrieval compared to yfinance

Code Comparison

pandas-datareader:

import pandas_datareader as pdr
data = pdr.get_data_yahoo("AAPL", start="2020-01-01", end="2021-01-01")

yfinance:

import yfinance as yf
ticker = yf.Ticker("AAPL")
data = ticker.history(start="2020-01-01", end="2021-01-01")

Both libraries provide similar functionality for fetching historical stock data. pandas-datareader offers a more straightforward approach with a single function call, while yfinance uses a Ticker object for more advanced features.

yfinance generally provides faster data retrieval and offers additional features like real-time data and company information. However, pandas-datareader is more versatile in terms of data sources and integrates seamlessly with the pandas ecosystem.

Choose pandas-datareader for stability and multiple data sources, or yfinance for speed and additional stock-specific features.

2,109

Common financial technical indicators implemented in Pandas.

Pros of finta

  • Focuses on technical analysis indicators and functions
  • Provides a wide range of financial indicators (over 80)
  • Lightweight and easy to integrate into existing projects

Cons of finta

  • Limited to technical analysis, doesn't provide market data retrieval
  • Less actively maintained compared to yfinance
  • Smaller community and fewer contributors

Code Comparison

finta example:

from finta import TA
import pandas as pd

df = pd.DataFrame(your_data)
sma = TA.SMA(df, period=14)
rsi = TA.RSI(df)

yfinance example:

import yfinance as yf

ticker = yf.Ticker("AAPL")
hist = ticker.history(period="1mo")
sma = hist['Close'].rolling(window=14).mean()

finta focuses on providing technical indicators, while yfinance is primarily used for fetching market data. yfinance offers built-in data retrieval and some basic analysis functions, whereas finta requires you to provide the data but offers a more comprehensive set of technical indicators.

finta is ideal for projects that already have data and need advanced technical analysis tools. yfinance is better suited for projects that need to fetch market data and perform basic analysis. For a complete solution, some developers use both libraries in conjunction.

Python module to get stock data from Yahoo! Finance

Pros of yahoo-finance

  • More established and mature project with a longer history
  • Offers a wider range of financial data beyond just stock prices
  • Better documentation and examples for beginners

Cons of yahoo-finance

  • Less frequently updated compared to yfinance
  • May have slower performance for large data requests
  • Limited support for real-time data

Code Comparison

yahoo-finance:

from yahoo_finance import Share
yahoo = Share('YHOO')
print(yahoo.get_price())
print(yahoo.get_trade_datetime())

yfinance:

import yfinance as yf
ticker = yf.Ticker("YHOO")
print(ticker.info['regularMarketPrice'])
print(ticker.info['regularMarketTime'])

Both libraries provide similar functionality for basic stock data retrieval, but yfinance offers a more streamlined and Pythonic API. The yahoo-finance library requires separate method calls for different data points, while yfinance allows access to multiple data points through a single 'info' dictionary. yfinance also provides more advanced features like downloading historical data and accessing options data, making it more versatile for complex financial analysis tasks.

Real time stock and option data.

Pros of wallstreet

  • Simpler API with fewer dependencies
  • Faster execution for basic stock data retrieval
  • Supports both synchronous and asynchronous operations

Cons of wallstreet

  • Less comprehensive data coverage compared to yfinance
  • Fewer advanced features and analysis tools
  • Smaller community and less frequent updates

Code Comparison

wallstreet:

from wallstreet import Stock
s = Stock('AAPL')
print(s.price)
print(s.change)

yfinance:

import yfinance as yf
ticker = yf.Ticker('AAPL')
print(ticker.info['regularMarketPrice'])
print(ticker.info['regularMarketChange'])

Both libraries provide easy access to basic stock data, but yfinance offers more detailed information and additional features. wallstreet's API is more straightforward for simple use cases, while yfinance provides a more comprehensive set of tools for in-depth analysis.

wallstreet is suitable for quick, basic stock data retrieval, whereas yfinance is better suited for more complex financial analysis and research tasks. The choice between the two depends on the specific requirements of your project and the depth of financial data needed.

A python wrapper for Alpha Vantage API for financial data.

Pros of Alpha Vantage

  • Offers a wider range of financial data, including forex and cryptocurrencies
  • Provides more detailed fundamental data and technical indicators
  • Has official API documentation and support

Cons of Alpha Vantage

  • Requires an API key for access
  • Has usage limits, especially for free tier users
  • May have slower data retrieval compared to yfinance

Code Comparison

Alpha Vantage:

from alpha_vantage.timeseries import TimeSeries
ts = TimeSeries(key='YOUR_API_KEY')
data, _ = ts.get_daily('AAPL')

yfinance:

import yfinance as yf
ticker = yf.Ticker('AAPL')
data = ticker.history(period='1d')

Both libraries offer simple ways to fetch stock data, but Alpha Vantage requires an API key and uses a different method structure. yfinance provides a more straightforward approach without the need for authentication, making it easier for quick data retrieval. However, Alpha Vantage's structure allows for more flexibility in accessing various types of financial data beyond just stock prices.

17,485

Zipline, a Pythonic Algorithmic Trading Library

Pros of Zipline

  • More comprehensive backtesting framework with built-in portfolio management
  • Supports custom data sources and complex trading strategies
  • Offers a simulation environment for testing algorithms

Cons of Zipline

  • Steeper learning curve due to its complexity
  • Less frequently updated compared to yfinance
  • Requires more setup and configuration

Code Comparison

Zipline example:

from zipline.api import order, record, symbol

def initialize(context):
    context.asset = symbol('AAPL')

def handle_data(context, data):
    order(context.asset, 10)
    record(AAPL=data.current(context.asset, 'price'))

yfinance example:

import yfinance as yf

aapl = yf.Ticker("AAPL")
hist = aapl.history(period="1mo")
print(hist['Close'])

Zipline provides a more structured approach for algorithmic trading, while yfinance offers simpler data retrieval and analysis. Zipline is better suited for complex backtesting and strategy development, whereas yfinance is more appropriate for quick data access and basic analysis tasks.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Download market data from Yahoo! Finance's API

*** IMPORTANT LEGAL DISCLAIMER ***


Yahoo!, Y!Finance, and Yahoo! finance are registered trademarks of Yahoo, Inc.

yfinance is not affiliated, endorsed, or vetted by Yahoo, Inc. It's an open-source tool that uses Yahoo's publicly available APIs, and is intended for research and educational purposes.

You should refer to Yahoo!'s terms of use (here, here, and here) for details on your rights to use the actual data downloaded. Remember - the Yahoo! finance API is intended for personal use only.


Python version PyPi version PyPi status PyPi downloads Travis-CI build status CodeFactor Star this repo Follow me on twitter

yfinance offers a threaded and Pythonic way to download market data from Yahoo!Ⓡ finance.

→ Check out this Blog post for a detailed tutorial with code examples.

Changelog »



Installation

Install yfinance using pip:

$ pip install yfinance --upgrade --no-cache-dir

With Conda.

To install with optional dependencies, replace optional with: nospam for caching-requests, repair for price repair, or nospam,repair for both:

$ pip install "yfinance[optional]"

Required dependencies , all dependencies.


Quick Start

The Ticker module

The Ticker module, which allows you to access ticker data in a more Pythonic way:

import yfinance as yf

msft = yf.Ticker("MSFT")

# get all stock info
msft.info

# get historical market data
hist = msft.history(period="1mo")

# show meta information about the history (requires history() to be called first)
msft.history_metadata

# show actions (dividends, splits, capital gains)
msft.actions
msft.dividends
msft.splits
msft.capital_gains  # only for mutual funds & etfs

# show share count
msft.get_shares_full(start="2022-01-01", end=None)

# show financials:
msft.calendar
msft.sec_filings
# - income statement
msft.income_stmt
msft.quarterly_income_stmt
# - balance sheet
msft.balance_sheet
msft.quarterly_balance_sheet
# - cash flow statement
msft.cashflow
msft.quarterly_cashflow
# see `Ticker.get_income_stmt()` for more options

# show holders
msft.major_holders
msft.institutional_holders
msft.mutualfund_holders
msft.insider_transactions
msft.insider_purchases
msft.insider_roster_holders

msft.sustainability

# show recommendations
msft.recommendations
msft.recommendations_summary
msft.upgrades_downgrades

# show analysts data
msft.analyst_price_targets
msft.earnings_estimate
msft.revenue_estimate
msft.earnings_history
msft.eps_trend
msft.eps_revisions
msft.growth_estimates

# Show future and historic earnings dates, returns at most next 4 quarters and last 8 quarters by default.
# Note: If more are needed use msft.get_earnings_dates(limit=XX) with increased limit argument.
msft.earnings_dates

# show ISIN code - *experimental*
# ISIN = International Securities Identification Number
msft.isin

# show options expirations
msft.options

# show news
msft.news

# get option chain for specific expiration
opt = msft.option_chain('YYYY-MM-DD')
# data available via: opt.calls, opt.puts

If you want to use a proxy server for downloading data, use:

import yfinance as yf

msft = yf.Ticker("MSFT")

msft.history(..., proxy="PROXY_SERVER")
msft.get_actions(proxy="PROXY_SERVER")
msft.get_dividends(proxy="PROXY_SERVER")
msft.get_splits(proxy="PROXY_SERVER")
msft.get_capital_gains(proxy="PROXY_SERVER")
msft.get_balance_sheet(proxy="PROXY_SERVER")
msft.get_cashflow(proxy="PROXY_SERVER")
msft.option_chain(..., proxy="PROXY_SERVER")
...

Multiple tickers

To initialize multiple Ticker objects, use

import yfinance as yf

tickers = yf.Tickers('msft aapl goog')

# access each ticker using (example)
tickers.tickers['MSFT'].info
tickers.tickers['AAPL'].history(period="1mo")
tickers.tickers['GOOG'].actions

To download price history into one table:

import yfinance as yf
data = yf.download("SPY AAPL", period="1mo")

yf.download() and Ticker.history() have many options for configuring fetching and processing. Review the Wiki for more options and detail.

Logging

yfinance now uses the logging module to handle messages, default behaviour is only print errors. If debugging, use yf.enable_debug_mode() to switch logging to debug with custom formatting.

Smarter scraping

Install the nospam packages for smarter scraping using pip (see Installation). These packages help cache calls such that Yahoo is not spammed with requests.

To use a custom requests session, pass a session= argument to the Ticker constructor. This allows for caching calls to the API as well as a custom way to modify requests via the User-agent header.

import requests_cache
session = requests_cache.CachedSession('yfinance.cache')
session.headers['User-agent'] = 'my-program/1.0'
ticker = yf.Ticker('msft', session=session)
# The scraped response will be stored in the cache
ticker.actions

Combine requests_cache with rate-limiting to avoid triggering Yahoo's rate-limiter/blocker that can corrupt data.

from requests import Session
from requests_cache import CacheMixin, SQLiteCache
from requests_ratelimiter import LimiterMixin, MemoryQueueBucket
from pyrate_limiter import Duration, RequestRate, Limiter
class CachedLimiterSession(CacheMixin, LimiterMixin, Session):
    pass

session = CachedLimiterSession(
    limiter=Limiter(RequestRate(2, Duration.SECOND*5)),  # max 2 requests per 5 seconds
    bucket_class=MemoryQueueBucket,
    backend=SQLiteCache("yfinance.cache"),
)

Managing Multi-Level Columns

The following answer on Stack Overflow is for How to deal with multi-level column names downloaded with yfinance?

  • yfinance returns a pandas.DataFrame with multi-level column names, with a level for the ticker and a level for the stock price data
    • The answer discusses:
      • How to correctly read the the multi-level columns after saving the dataframe to a csv with pandas.DataFrame.to_csv
      • How to download single or multiple tickers into a single dataframe with single level column names and a ticker column

Persistent cache store

To reduce Yahoo, yfinance store some data locally: timezones to localize dates, and cookie. Cache location is:

  • Windows = C:/Users/<USER>/AppData/Local/py-yfinance
  • Linux = /home/<USER>/.cache/py-yfinance
  • MacOS = /Users/<USER>/Library/Caches/py-yfinance

You can direct cache to use a different location with set_tz_cache_location():

import yfinance as yf
yf.set_tz_cache_location("custom/cache/location")
...

Developers: want to contribute?

yfinance relies on community to investigate bugs and contribute code. Developer guide: https://github.com/ranaroussi/yfinance/discussions/1084


Legal Stuff

yfinance is distributed under the Apache Software License. See the LICENSE.txt file in the release for details.

AGAIN - yfinance is not affiliated, endorsed, or vetted by Yahoo, Inc. It's an open-source tool that uses Yahoo's publicly available APIs, and is intended for research and educational purposes. You should refer to Yahoo!'s terms of use (here, here, and here) for details on your rights to use the actual data downloaded.


P.S.

Please drop me an note with any feedback you have.

Ran Aroussi