yfinance

repository·main·Indexed 12 days ago

https://github.com/ranaroussi/yfinance

A Python library for fetching financial and market data from Yahoo! Finance's publicly available APIs. It provides core components such as Ticker, Tickers, and download for market data, as well as tools for sector and industry information, market screening, and live streaming via WebSocket. Features include a price repair mechanism to fix common data errors in non-US markets, persistent caching for timezones and cookies, and configurable network and locale settings.

Tokens
10.2K
Snippets
52
Records
65
Agent score
97%

What's inside yfinance

  1. Overview of the yfinance Public API

    main

    The yfinance package provides a comprehensive interface for retrieving market data from Yahoo! Finance. The public API is organized into several functional areas:

    • Ticker Data: Use Ticker for single assets and Tickers for managing multiple assets.
    • Market & Calendars: Access market summaries via Market and event calendars via Calendars.
    • Data Downloading: Use the download function for bulk historical market data retrieval.
    • Search & Lookup: Use Search for general search results and Lookup for specific ticker lookups.
    • Live Streaming: Access live market data via WebSocket (synchronous) or AsyncWebSocket (asynchronous).
    • Screener & Queries: Use EquityQuery, FundQuery, and ETFQuery to build filters, and execute them using screen.
    • Domain Data: Access sector and industry information via Sector and Industry classes.
    • Authentication & Config: Manage authentication via Auth and global settings via config.
  2. Overview of yfinance main components

    main

    The yfinance library provides several core components for interacting with market data:

    • Ticker: Access data for a single ticker.
    • Tickers: Access data for multiple tickers.
    • download: Download market data for multiple tickers at once.
    • Market: Retrieve information about a specific market.
    • WebSocket and AsyncWebSocket: Access live streaming data.
    • Search: Retrieve quotes and news via search.
    • Sector and Industry: Access sector and industry-specific information.
    • EquityQuery and Screener: Build queries to screen the market.
  3. Query market data using Screener modules

    main

    You can query market data based on sectors and industries using the yfinance screener modules. The library provides specialized query classes for different asset types to filter and find market data:

    • EquityQuery: For querying individual stocks/equities.
    • FundQuery: For querying mutual funds.
    • ETFQuery: For querying Exchange Traded Funds (ETFs).
    • screen: A general function/module for performing screen operations.

    To perform specific queries, you should inspect the valid_fields and valid_values attributes of the relevant query class to see which operand values and parameters are supported for your specific asset type.

    import yfinance as yf
    
    # Example conceptual usage (exact implementation depends on class methods)
    # Use EquityQuery, FundQuery, or ETFQuery to filter market data
    query = yf.EquityQuery(field='sector', value='Technology')
    # ... perform screen/query ...
  4. How authentication works in yfinance

    main

    The yfinance.Auth module allows you to log in to Yahoo! Finance, verify your login state, and check your account's subscription tier.

    Important Limitation: yfinance cannot automate login using a username and password because Yahoo Finance requires solving a reCAPTCHA, which blocks automated scripts. Instead, you must manually obtain authentication cookies from your browser and provide them to the library.

  5. How the yfinance branching model works

    main

    The project uses a two-layer branch model to separate active development from stable releases:

    • dev: The primary target for most contributions. It is used for new features, bug fixes, collective testing, and stabilization.
    • main: The stable branch used for creating PIP releases.

    Note on Pull Requests: While branches target main by default, most contributions should target the dev branch. Direct merges to main are reserved for critical fixes (e.g., when yfinance is massively broken or a fix is simple and isolated) or non-code changes like documentation.

  6. Use the Market class to access market data

    main

    The Market class provides a Pythonic interface to access various types of market data from Yahoo Finance. It serves as the primary entry point for querying data across different global markets and asset classes.

    import yfinance as yf
    
    # Example usage of the Market class
    market = yf.Market()
    # Access market data via the market instance
  7. Get upcoming market events with the Calendars class

    main

    The Calendars class in yfinance provides access to information about upcoming market events, such as earnings announcements. You can use this class to retrieve schedules for specific tickers or general market calendars.

    import yfinance as yf
    
    # Example usage pattern for Calendars
    # Note: Actual implementation details depend on the specific methods available in the Calendars class
    calendars = yf.Calendars()
    # ... call methods to retrieve event data
  8. Use the Search module to find market data

    main

    The Search module provides a Pythonic interface to access search data from Yahoo! Finance. It is used to query and discover relevant market entities.

    # Example usage from examples/search.py
    import yfinance as yf
    
    # The Search module allows you to access search data in a Pythonic way.
    # (Refer to examples/search.py for specific implementation details)
  9. What errors does price repair fix?

    main

    The repair=True feature addresses several categories of data inaccuracies commonly found in non-US market data from Yahoo Finance:

    Price Errors

    • Missing dividend adjustment: Manually applies dividend adjustments to Adj Close if they are missing in the raw data.
    • Missing split adjustment: Applies stock split adjustments if the preceding price data is unadjusted.
    • Missing data: Reconstructs missing or corrupt rows using smaller intervals (e.g., using 1h data to fix 1d data).
    • 100x errors: Detects and fixes currency mixups (e.g., $/cents or £/pence) where prices are off by a factor of 100.

    Dividend Errors

    • Adjustment issues: Fixes missing adjustments or adjustments that are 100x too large/small.
    • Duplicates: Removes duplicate dividends reported within a 7-day window.
    • Magnitude errors: Fixes dividends that are 100x too large/small relative to the ex-dividend price drop.
    • Date errors: Corrects incorrect ex-dividend dates where the price drop occurs several days/weeks later.
    • Double-counted capital gains: Fixes instances where both dividends and capital gains are applied to the price drop, causing an over-adjustment.
  10. How yfinance handles persistent caching

    main

    To reduce the number of requests sent to Yahoo Finance, yfinance stores certain data locally, specifically timezones (used to localize dates) and cookies. By default, this cache is stored in platform-specific directories:

    • Windows: C:/Users/<USER>/AppData/Local/py-yfinance
    • Linux: /home/<USER>/.cache/py-yfinance
    • MacOS: /Users/<USER>/Library/Caches/py-yfinance
  11. Handle multi-level column names in yfinance DataFrames

    main

    When downloading data for multiple tickers, yfinance returns a pandas.DataFrame with a multi-level column index. The levels typically consist of the Ticker (e.g., 'AAPL') and the Price Data Type (e.g., 'Close', 'Open', 'Volume').

    To manage this structure, you can follow patterns discussed in the community (e.g., on Stack Overflow) to either flatten the columns or restructure the data for easier consumption.