or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

bulk-data.mdconfig-utils.mdindex.mdlive-streaming.mdmarket-sector.mdscreening.mdsearch-lookup.mdticker-data.md
tile.json

tessl/pypi-yfinance

Download market data from Yahoo! Finance API

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/yfinance@0.2.x

To install, run

npx @tessl/cli install tessl/pypi-yfinance@0.2.0

index.mddocs/

yfinance

A 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.

Package Information

  • Package Name: yfinance
  • Language: Python
  • Installation: pip install yfinance

Core Imports

import yfinance as yf

For 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, screen

Basic Usage

import 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)

Architecture

yfinance provides multiple access patterns:

  • Individual Ticker Access: Ticker class for detailed single-symbol analysis
  • Bulk Data Operations: download() function and Tickers class for multi-symbol operations
  • Real-time Streaming: WebSocket and AsyncWebSocket for live data feeds
  • Search & Discovery: Search and Lookup classes for finding financial instruments
  • Market Intelligence: Market, Sector, and Industry classes for broader market analysis
  • Custom Screening: EquityQuery, FundQuery, and screen() for filtering instruments

The library is built around Yahoo Finance's public APIs and provides comprehensive error handling, data caching, and rate limiting.

Capabilities

Single Ticker Data Access

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: tuple

Single Ticker Data Access

Bulk Data Operations

Efficient 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: ...

Bulk Data Operations

Search and Lookup

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: ...

Search and Lookup

Real-time Data Streaming

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): ...

Real-time Data Streaming

Market and Sector Analysis

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.DataFrame

Market and Sector Analysis

Custom Screening

Build 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]

Custom Screening

Configuration and Utilities

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): ...

Configuration and Utilities

Common Data Formats

  • Historical Data: pandas DataFrame with OHLCV columns and datetime index
  • Financial Statements: pandas DataFrame with financial metrics as columns and periods as index
  • Company Information: Dictionary with key-value pairs for company metadata
  • Options Chains: Named tuple with .calls, .puts, and .underlying attributes
  • News Articles: List of dictionaries with article metadata and content
  • Search Results: List of dictionaries with instrument metadata

Error Handling

yfinance includes comprehensive error handling for common scenarios:

  • Invalid ticker symbols
  • Network connectivity issues
  • API rate limiting
  • Data unavailability
  • Malformed requests

Most methods will return empty DataFrames or None values rather than raising exceptions, allowing for graceful handling of missing data.