Download market data from Yahoo! Finance API
npx @tessl/cli install tessl/pypi-yfinance@0.2.0A Python library that provides a Pythonic way to fetch financial and market data from Yahoo! Finance's API. It offers comprehensive functionality for downloading historical market data, real-time quotes, financial statements, and other financial information for stocks, ETFs, mutual funds, currencies, and cryptocurrencies.
pip install yfinanceimport yfinance as yfFor specific components:
from yfinance import Ticker, download, Search, Lookup
from yfinance import WebSocket, AsyncWebSocket
from yfinance import Market, Sector, Industry
from yfinance import EquityQuery, FundQuery, screenimport yfinance as yf
# Single ticker data
ticker = yf.Ticker("AAPL")
info = ticker.info
history = ticker.history(period="1mo")
# Multiple ticker download
data = yf.download(["AAPL", "GOOGL", "MSFT"], period="1mo")
# Search for companies
search = yf.Search("Apple")
quotes = search.quotes
# Real-time streaming
def handle_message(msg):
print(msg)
ws = yf.WebSocket()
ws.subscribe(["AAPL", "GOOGL"])
ws.listen(handle_message)yfinance provides multiple access patterns:
Ticker class for detailed single-symbol analysisdownload() function and Tickers class for multi-symbol operationsWebSocket and AsyncWebSocket for live data feedsSearch and Lookup classes for finding financial instrumentsMarket, Sector, and Industry classes for broader market analysisEquityQuery, FundQuery, and screen() for filtering instrumentsThe library is built around Yahoo Finance's public APIs and provides comprehensive error handling, data caching, and rate limiting.
Comprehensive data access for individual financial instruments including historical prices, financial statements, ownership data, analyst recommendations, options chains, and company information.
class Ticker:
def __init__(self, ticker: str, session=None, proxy=None): ...
def history(self, period: str = "1mo", interval: str = "1d",
start=None, end=None, **kwargs) -> pd.DataFrame: ...
def option_chain(self, date=None, tz=None) -> namedtuple: ...
# Properties for financial data
info: dict
financials: pd.DataFrame
balance_sheet: pd.DataFrame
cash_flow: pd.DataFrame
earnings: pd.DataFrame
recommendations: pd.DataFrame
options: tupleEfficient downloading and management of multiple financial instruments with threading support and various data formatting options.
def download(tickers, start=None, end=None, period=None, interval="1d",
group_by='column', auto_adjust=None, threads=True, **kwargs) -> pd.DataFrame: ...
class Tickers:
def __init__(self, tickers, session=None): ...
def history(self, **kwargs) -> pd.DataFrame: ...
def news(self) -> dict: ...Search for financial instruments by name or lookup instruments by category with comprehensive filtering and result management.
class Search:
def __init__(self, query: str, max_results: int = 8, **kwargs): ...
def search(self) -> 'Search': ...
# Properties
quotes: list
news: list
all: dict
class Lookup:
def __init__(self, query: str, **kwargs): ...
def get_stock(self, count: int = 25) -> pd.DataFrame: ...
def get_etf(self, count: int = 25) -> pd.DataFrame: ...
def get_mutualfund(self, count: int = 25) -> pd.DataFrame: ...Live financial data streaming using WebSocket connections with both synchronous and asynchronous support.
class WebSocket:
def __init__(self, url: str = "wss://streamer.finance.yahoo.com/?version=2",
verbose: bool = True): ...
def subscribe(self, symbols: Union[str, List[str]]): ...
def listen(self, message_handler: Optional[Callable] = None): ...
def close(self): ...
class AsyncWebSocket:
async def subscribe(self, symbols: Union[str, List[str]]): ...
async def listen(self, message_handler: Optional[Callable] = None): ...Market status information, sector performance data, and industry-level analysis for broader market intelligence.
class Market:
def __init__(self, market: str, session=None, timeout: int = 30): ...
# Properties
status: dict
summary: dict
class Sector:
def __init__(self, key: str, session=None): ...
# Properties
top_etfs: Dict[str, str]
top_mutual_funds: Dict[str, str]
industries: pd.DataFrame
class Industry:
def __init__(self, key: str, session=None): ...
# Properties
top_performing_companies: pd.DataFrame
top_growth_companies: pd.DataFrameBuild custom queries to screen and filter financial instruments based on various criteria with predefined screening options.
class EquityQuery:
def __init__(self, operator: str, operand: list): ...
class FundQuery:
def __init__(self, operator: str, operand: list): ...
def screen(query: Union[str, EquityQuery, FundQuery],
size: int = None, sortField: str = None, **kwargs) -> dict: ...
PREDEFINED_SCREENER_QUERIES: Dict[str, str]Global configuration options, debugging utilities, and cache management for optimal performance and troubleshooting.
def set_config(proxy=None): ...
def enable_debug_mode(): ...
def set_tz_cache_location(cache_dir: str): ....calls, .puts, and .underlying attributesyfinance includes comprehensive error handling for common scenarios:
Most methods will return empty DataFrames or None values rather than raising exceptions, allowing for graceful handling of missing data.