### Install Documentation Dependencies Source: https://ranaroussi.github.io/yfinance/development/documentation.html Installs Sphinx and related themes/plugins required for building the documentation locally. Use this command after cloning the repository. ```bash pip install -r requirements.txt pip install Sphinx==8.0.2 pydata-sphinx-theme==0.15.4 Jinja2==3.1.4 sphinx-copybutton==0.5.2 ``` -------------------------------- ### Install yfinance Source: https://ranaroussi.github.io/yfinance/index.html Install the yfinance library using pip. This is the first step before using any of its functionalities. ```bash $ pip install yfinance ``` -------------------------------- ### Install yfinance from a Git Branch using PIP Source: https://ranaroussi.github.io/yfinance/development/running.html Use this command to install yfinance directly from a specific branch on GitHub using pip. Replace {user}/{repo} and {branch} with your details. ```bash pip install git+https://github.com/{user}/{repo}.git@{branch} ``` ```bash pip install git+https://github.com/ranaroussi/yfinance.git@feature/name ``` -------------------------------- ### Duplicate Dividend (within 7 days) Example Source: https://ranaroussi.github.io/yfinance/advanced/price_repair.html Shows an example of a duplicate dividend entry within a 7-day period. The duplicate dividend is removed or adjusted. ```python # ORIGINAL: Close Adj Close Dividends 2023-05-10 00:00:00+02:00 70.580002 70.352142 0.21 2023-05-09 00:00:00+02:00 65.739998 65.318443 0.21 2023-05-08 00:00:00+02:00 66.379997 65.745682 0.00 ``` ```python # REPAIRED: Close Adj Close Dividends 2023-05-10 00:00:00+02:00 70.580002 70.352142 0.00 2023-05-09 00:00:00+02:00 65.739998 65.527764 0.21 2023-05-08 00:00:00+02:00 66.379997 65.956371 0.00 ``` -------------------------------- ### Serve Local Documentation Source: https://ranaroussi.github.io/yfinance/development/documentation.html Starts a local HTTP server to view the generated HTML documentation in a web browser. Navigate to http://localhost:8000 after running this command. ```bash python -m http.server -d ./doc/_build/html ``` -------------------------------- ### Install yfinance without curl_cffi Source: https://ranaroussi.github.io/yfinance/advanced/install.html Installs yfinance using pip, excluding the `curl_cffi` package and falling back to standard requests. This is useful if `curl_cffi` causes issues or is not desired. ```bash curl -fsSL https://raw.githubusercontent.com/ranaroussi/yfinance/main/requirements.txt | grep -vi '^curl_cffi' | pip install -r /dev/stdin pip install --no-deps yfinance ``` -------------------------------- ### Search Module Examples Source: https://ranaroussi.github.io/yfinance/reference/yfinance.search.html Demonstrates how to use the Search module to retrieve stock quotes, news articles, and research related to a query. Requires importing the yfinance library. ```python import yfinance as yf # get list of quotes quotes = yf.Search("AAPL", max_results=10).quotes # get list of news news = yf.Search("Google", news_count=10).news # get list of related research research = yf.Search("apple", include_research=True).research ``` -------------------------------- ### Constructing a Fund Query Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.FundQuery.html This example demonstrates how to use the FundQuery class to build a filter for mutual funds. It combines multiple criteria using logical and comparison operators. ```python from yfinance import FundQuery FundQuery('and', [ FundQuery('eq', ['categoryname', 'Large Growth']), FundQuery('is-in', ['performanceratingoverall', 4, 5]), FundQuery('lt', ['initialinvestment', 100001]), FundQuery('lt', ['annualreturnnavy1categoryrank', 50]), FundQuery('eq', ['exchange', 'NAS']) ]) ``` -------------------------------- ### Example Usage of FundQuery Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.FundQuery.html Demonstrates how to use the FundQuery class to create a complex filter for 'Large Growth' mutual funds with specific performance and investment criteria. ```APIDOC ## Example ```python from yfinance import FundQuery # Constructing a filter for large growth funds large_growth_funds_filter = FundQuery('and', [ FundQuery('eq', ['categoryname', 'Large Growth']), FundQuery('is-in', ['performanceratingoverall', 4, 5]), FundQuery('lt', ['initialinvestment', 100001]), FundQuery('lt', ['annualreturnnavy1categoryrank', 50]), FundQuery('eq', ['exchange', 'NAS']) ]) ``` ``` -------------------------------- ### Get Info Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Retrieves general information about the ticker. ```APIDOC ## Get Info ### Description Returns general information about the ticker. ### Method get_info ### Returns dict: A dictionary containing various information about the company. ``` -------------------------------- ### Constructing an ETF Query Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.ETFQuery.html This example demonstrates how to build a query to find US ETFs with a performance rating of 4 or 5 and an intraday price greater than 10. It uses 'and', 'gt', 'is-in', and 'eq' operators. ```python from yfinance import ETFQuery ETFQuery('and', [ ETFQuery('gt', ['intradayprice', 10]), ETFQuery('is-in', ['performanceratingoverall', 4, 5]), ETFQuery('eq', ['region', 'us']) ]) ``` -------------------------------- ### AsyncWebSocket.listen() Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.AsyncWebSocket.html Starts listening for messages from the WebSocket server. A message handler can be provided to process incoming data. ```APIDOC ## AsyncWebSocket.listen() ### Description Start listening to messages from the WebSocket server. ### Parameters * **message_handler** (_Optional[Callable[[dict], None]]_) - Optional function to handle received messages. ### Method `async def listen(message_handler=None)` ``` -------------------------------- ### Constructing an EquityQuery Filter Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.EquityQuery.html This example demonstrates how to create a predefined Yahoo query named 'aggressive_small_caps' using the EquityQuery class. It filters for stocks in specific exchanges ('NMS', 'NYQ') and with an earnings per share growth less than 15. ```python from yfinance import EquityQuery EquityQuery('and', [ EquityQuery('is-in', ['exchange', 'NMS', 'NYQ']), EquityQuery('lt', ["epsgrowth.lasttwelvemonths", 15]) ]) ``` -------------------------------- ### WebSocket.listen() Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.WebSocket.html Starts listening for incoming messages from the WebSocket server. An optional message handler can be provided to process received data. ```APIDOC ## WebSocket.listen() ### Description Start listening to messages from the WebSocket server. ### Parameters * **message_handler** (_Optional_[Callable[[dict], None]]_) – Optional function to handle received messages. ``` -------------------------------- ### Missing Dividend Adjustment Example Source: https://ranaroussi.github.io/yfinance/advanced/price_repair.html Demonstrates a case where the dividend adjustment was missing. The `Repaired?` column is not set to `True` as only `Adj Close` is modified. ```python # ORIGINAL: Close Adj Close Dividends 2024-07-08 00:00:00+08:00 4.33 4.33 0.335715 2024-07-04 00:00:00+08:00 4.83 4.83 0.000000 ``` ```python # REPAIRED: Close Adj Close Dividends 2024-07-08 00:00:00+08:00 4.33 4.330000 0.335715 2024-07-04 00:00:00+08:00 4.83 4.494285 0.000000 ``` -------------------------------- ### Import yfinance Library Source: https://ranaroussi.github.io/yfinance/index.html Import the yfinance library and create a Ticker object for a specific stock symbol. This is a common starting point for data retrieval. ```python import yfinance as yf dat = yf.Ticker("MSFT") ``` -------------------------------- ### Run a Custom Equity Screen Query Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.screen.html Execute a custom screening query for equities using the EquityQuery object. This example filters for stocks with a percent change greater than 3% and in the 'us' region, sorted by percent change. ```python import yfinance as yf from yfinance import EquityQuery q = EquityQuery('and', [ EquityQuery('gt', ['percentchange', 3]), EquityQuery('eq', ['region', 'us']) ]) response = yf.screen(q, sortField = 'percentchange', sortAsc = True) ``` -------------------------------- ### Chain Ticker with Sector and Industry Source: https://ranaroussi.github.io/yfinance/reference/yfinance.sector_industry.html Illustrates how to link Ticker objects with Sector and Industry modules. Shows retrieving sector and industry keys from a Ticker and then using those to get ticker data. ```python import yfinance as yf # Ticker to Sector and Industry msft = yf.Ticker('MSFT') tech = yf.Sector(msft.info.get('sectorKey')) software = yf.Industry(msft.info.get('industryKey')) # Sector and Industry to Ticker tech_ticker = tech.ticker tech_ticker.info software_ticker = software.ticker software_ticker.history() ``` -------------------------------- ### Get Earnings Calendar with Default Parameters Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Calendars.html Retrieves the earnings calendar using default parameters. Ensure yfinance is imported as yf. ```python import yfinance as yf calendars = yf.Calendars() earnings_calendar = calendars.get_earnings_calendar(limit=50) print(earnings_calendar) ``` -------------------------------- ### Missing Split Adjustment Example Source: https://ranaroussi.github.io/yfinance/advanced/price_repair.html Illustrates a scenario where a stock split occurred, but preceding price data was not adjusted. This repair requires the date range to include one day after the split for calibration. -------------------------------- ### Dividend Adjustment Too Small Example Source: https://ranaroussi.github.io/yfinance/advanced/price_repair.html Presents a case where the dividend adjustment was too small. The `Adj Close` is corrected to reflect the actual dividend amount. ```python # ORIGINAL: Close Adj Close Dividends 2024-06-13 00:00:00+01:00 3.185 3.185000 0.05950 2024-06-12 00:00:00+01:00 3.270 3.269405 0.00000 ``` ```python # REPAIRED: Close Adj Close Dividends 2024-06-13 00:00:00+01:00 3.185 3.185000 0.05950 2024-06-12 00:00:00+01:00 3.270 3.210500 0.00000 ``` -------------------------------- ### Lookup Module - Get Cryptocurrencies Source: https://ranaroussi.github.io/yfinance/reference/yfinance.search.html Fetches a list of cryptocurrency instruments for a given ticker symbol using the Lookup module. Requires importing the yfinance library. ```python import yfinance as yf # Get Cryptocurrencies cryptocurrency = yf.Lookup("AAPL").cryptocurrency cryptocurrency = yf.Lookup("AAPL").get_cryptocurrency(count=100) ``` -------------------------------- ### Get Economic Events Calendar Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Calendars.html Retrieves economic events calendar data. Allows specifying start and end dates, a limit for results, and an offset for pagination. Can force a re-query if cache exists. ```python calendars.get_economic_events_calendar(_start ='2025-11-08', _end ='2025-11-08', _limit =12, _offset =0, _force =False) ``` -------------------------------- ### Get Splits Calendar Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Calendars.html Fetches stock splits calendar data. Parameters include start and end dates, a limit for the number of results, and an offset for pagination. The force parameter can be used to refresh data. ```python calendars.get_splits_calendar(_start ='2025-11-08', _end ='2025-11-08', _limit =12, _offset =0, _force =False) ``` -------------------------------- ### Lookup Module - Get Stocks Source: https://ranaroussi.github.io/yfinance/reference/yfinance.search.html Fetches a list of stock instruments for a given ticker symbol using the Lookup module. Requires importing the yfinance library. ```python import yfinance as yf # Get Stocks stock = yf.Lookup("AAPL").stock stock = yf.Lookup("AAPL").get_stock(count=100) ``` -------------------------------- ### Add Local yfinance Clone to Python Path Source: https://ranaroussi.github.io/yfinance/development/running.html If you have cloned the yfinance repository locally, you can add its path to your Python environment. This is useful for project-specific installations. Ensure you are adding the correct path to the cloned repository. ```python import sys sys.path.insert(0, "path/to/downloaded/yfinance") ``` -------------------------------- ### Initialize Sector and Industry Objects Source: https://ranaroussi.github.io/yfinance/reference/yfinance.sector_industry.html Demonstrates how to initialize Sector and Industry objects using their respective keys. Shows common information and sector/industry-specific attributes. ```python import yfinance as yf tech = yf.Sector('technology') software = yf.Industry('software-infrastructure') # Common information tech.key tech.name tech.symbol tech.ticker tech.overview tech.top_companies tech.research_reports # Sector information tech.top_etfs tech.top_mutual_funds tech.industries # Industry information software.sector_key software.sector_name software.top_performing_companies software.top_growth_companies ``` -------------------------------- ### __init__ Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.EquityQuery.html Initializes an EquityQuery object. This method allows users to define equity queries using specified operators and operands. ```APIDOC ## __init__ ### Description Initializes an EquityQuery object with a specified operator and operand. ### Parameters #### Path Parameters - **operator** (Literal['eq', 'is-in', 'btwn', 'gt', 'lt', 'gte', 'lte', 'and', 'or']) - Required - The operator to use for the query. - **operand** (List[QueryBase] | List[str] | List[Real]) - Required - The operand(s) for the query. This can be a list of QueryBase objects, strings, or real numbers. ### Method __init__ ``` -------------------------------- ### Initialize and Query yfinance Calendars Source: https://ranaroussi.github.io/yfinance/reference/yfinance.calendars.html Demonstrates initializing the Calendars class with default and custom date ranges, accessing calendar properties, and performing manual queries for various event types. ```python import yfinance as yf from datetime import datetime, timedelta # Default init (today + 7 days) calendar = yf.Calendars() # Today's events: calendar of 1 day tomorrow = datetime.now() + timedelta(days=1) calendar = yf.Calendars(end=tomorrow) # Default calendar queries - accessing the properties will fetch the data from YF calendar.earnings_calendar calendar.ipo_info_calendar calendar.splits_calendar calendar.economic_events_calendar # Manual queries calendar.get_earnings_calendar() calendar.get_ipo_info_calendar() calendar.get_splits_calendar() calendar.get_economic_events_calendar() ``` -------------------------------- ### top_etfs Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Sector.html Gets the top ETFs for the sector. ```APIDOC ## top_etfs ### Description Gets the top ETFs for the sector. ### Returns A dictionary of ETF symbols and names. Return type: Dict[str, str] ``` -------------------------------- ### Initialize Market Object and Access Data Source: https://ranaroussi.github.io/yfinance/reference/yfinance.market.html Demonstrates how to initialize a Market object for a specific region (EUROPE) and access its status and summary attributes. ```python import yfinance as yf EUROPE = yf.Market("EUROPE") status = EUROPE.status summary = EUROPE.summary ``` -------------------------------- ### Using a Proxy Server Source: https://ranaroussi.github.io/yfinance/reference/yfinance.ticker_tickers.html Illustrates how to configure and use a proxy server for downloading data using Ticker methods. ```APIDOC ## Proxy Server Configuration ### Description Allows specifying a proxy server for downloading data through various Ticker methods. ### Usage Examples ```python import yfinance as yf msft = yf.Ticker("MSFT") # Example of using proxy with history method # msft.history(proxy="PROXY_SERVER") # Other methods that support proxy: # 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") ``` ``` -------------------------------- ### top_mutual_funds Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Sector.html Gets the top mutual funds for the sector. ```APIDOC ## top_mutual_funds ### Description Gets the top mutual funds for the sector. ### Returns A dictionary of mutual fund symbols and names. Return type: Dict[str, str] ``` -------------------------------- ### Get Growth Estimates Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Retrieves growth estimates for the ticker. ```APIDOC ## Get Growth Estimates ### Description Returns growth estimates for the ticker. ### Method get_growth_estimates ### Parameters * **as_dict** (bool) - Optional - If True, returns the data as a Python dictionary. Defaults to False. ### Returns DataFrame or dict: Data indexed by time periods with columns like stock, industry, sector, index. ``` -------------------------------- ### Get Funds Data Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Retrieves fund-related data for the ticker. ```APIDOC ## Get Funds Data ### Description Returns fund-related data for the ticker. ### Method get_funds_data ### Returns FundsData | None: Fund data or None if not available. ``` -------------------------------- ### Get Fast Info Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Retrieves fast-access information for the ticker. ```APIDOC ## Get Fast Info ### Description Returns fast-access information for the ticker. ### Method get_fast_info ### Returns dict: A dictionary containing quick-access financial information. ``` -------------------------------- ### Get Earnings Estimate Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Retrieves earnings estimates for the ticker. ```APIDOC ## Get Earnings Estimate ### Description Returns earnings estimates for the ticker. ### Method get_earnings_estimate ### Parameters * **as_dict** (bool) - Optional - If True, returns the data as a Python dictionary. Defaults to False. ### Returns DataFrame or dict: Data indexed by quarter/year with columns like numberOfAnalysts, avg, low, high, yearAgoEps, growth. ``` -------------------------------- ### live Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Establishes a live data connection for the ticker. ```APIDOC ## live ### Description Establishes a live data connection for the ticker. ### Method `live(_message_handler =None_, _verbose =True_)` ### Parameters * **_message_handler** (callable) - Optional - A function to handle incoming messages. * **_verbose** (bool) - Optional - If True, prints verbose output. Defaults to True. ### Response Initiates a live data stream. ``` -------------------------------- ### Get Dividends Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Retrieves dividend data for a specified period. ```APIDOC ## Get Dividends ### Description Returns dividends for the ticker. ### Method get_dividends ### Parameters * **period** (str) - Optional - Defaults to 'max'. Specifies the period for which to retrieve dividends. ``` -------------------------------- ### Using Proxy Server with Ticker Methods Source: https://ranaroussi.github.io/yfinance/reference/yfinance.ticker_tickers.html Illustrates how to configure a proxy server for various yfinance Ticker methods when downloading data, ensuring requests are routed through the specified proxy. ```python 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") ... ``` -------------------------------- ### Get Major Holders Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Retrieves data on major holders for the ticker. ```APIDOC ## Get Major Holders ### Description Returns data on major holders for the ticker. ### Method get_major_holders ### Parameters * **as_dict** (bool) - Optional - If True, returns the data as a Python dictionary. Defaults to False. ``` -------------------------------- ### Initialize and Use Ticker Object Source: https://ranaroussi.github.io/yfinance/reference/yfinance.ticker_tickers.html Demonstrates how to initialize a Ticker object for a single stock and access various data points like historical data, options, financials, calendar, analyst targets, and live data. ```python import yfinance as yf dat = yf.Ticker("MSFT") # get historical market data dat.history(period='1mo') # options dat.option_chain(dat.options[0]).calls # get financials dat.balance_sheet dat.quarterly_income_stmt # dates dat.calendar # general info dat.info # analysis dat.analyst_price_targets # websocket dat.live() ``` -------------------------------- ### Get Institutional Holders Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Retrieves data on institutional holders for the ticker. ```APIDOC ## Get Institutional Holders ### Description Returns data on institutional holders for the ticker. ### Method get_institutional_holders ### Parameters * **as_dict** (bool) - Optional - If True, returns the data as a Python dictionary. Defaults to False. ``` -------------------------------- ### Get Insider Transactions Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Retrieves data on insider transactions for the ticker. ```APIDOC ## Get Insider Transactions ### Description Returns data on insider transactions for the ticker. ### Method get_insider_transactions ### Parameters * **as_dict** (bool) - Optional - If True, returns the data as a Python dictionary. Defaults to False. ``` -------------------------------- ### WebSocket Initialization Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.WebSocket.html Initializes the WebSocket client for streaming real-time pricing data. Users can specify the WebSocket server URL and control verbose output. ```APIDOC ## WebSocket Class ### Description Synchronous WebSocket client for streaming real time pricing data. ### Parameters * **url** (_str_) – The WebSocket server URL. Defaults to Yahoo Finance’s WebSocket URL. * **verbose** (_bool_) – Flag to enable or disable print statements. Defaults to True. ``` -------------------------------- ### Get Insider Purchases Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Retrieves data on insider purchases for the ticker. ```APIDOC ## Get Insider Purchases ### Description Returns data on insider purchases for the ticker. ### Method get_insider_purchases ### Parameters * **as_dict** (bool) - Optional - If True, returns the data as a Python dictionary. Defaults to False. ``` -------------------------------- ### Run All Tests Source: https://ranaroussi.github.io/yfinance/development/testing.html Discover and run all tests within the `tests` directory and its subdirectories. ```bash python -m unittest discover -s tests ``` -------------------------------- ### Get Earnings History Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Retrieves historical earnings data for the ticker. ```APIDOC ## Get Earnings History ### Description Returns historical earnings data for the ticker. ### Method get_earnings_history ### Parameters * **as_dict** (bool) - Optional - If True, returns the data as a Python dictionary. Defaults to False. ### Returns DataFrame or dict: Data indexed by DatetimeIndex with columns like epsEstimate, epsActual, epsDifference, surprisePercent. ``` -------------------------------- ### get_recommendations Source: https://ranaroussi.github.io/yfinance/reference/yfinance.analysis.html Returns a DataFrame with the recommendations. Columns include period, strongBuy, buy, hold, sell, and strongSell. ```APIDOC ## get_recommendations ### Description Returns a DataFrame with the recommendations. Columns include period, strongBuy, buy, hold, sell, and strongSell. ### Method GET ### Endpoint /analysis/recommendations ### Parameters #### Query Parameters - **as_dict** (bool) - Optional - If True, returns a dictionary; otherwise, returns a DataFrame. ### Response #### Success Response (200) - **recommendations** (DataFrame or dict) - DataFrame with recommendation data. ``` -------------------------------- ### Get Earnings Dates Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Retrieves a DataFrame of earnings dates for the ticker. ```APIDOC ## Get Earnings Dates ### Description Returns a DataFrame of earnings dates for the ticker. ### Method get_earnings_dates ### Parameters * **limit** (int) - Optional - Defaults to 12. The number of earnings dates to retrieve. * **offset** (int) - Optional - Defaults to 0. The offset for retrieving earnings dates. ``` -------------------------------- ### Build Documentation Locally with Sphinx Source: https://ranaroussi.github.io/yfinance/development/documentation.html Generates HTML documentation from the reStructuredText source files using Sphinx. The output is placed in the specified build directory. ```bash sphinx-build -b html doc/source doc/_build/html ``` -------------------------------- ### Get ISIN Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Retrieves the International Securities Identification Number (ISIN) for the ticker. ```APIDOC ## Get ISIN ### Description Returns the International Securities Identification Number (ISIN) for the ticker. ### Method get_isin ### Returns str | None: The ISIN string or None if not available. ``` -------------------------------- ### AsyncWebSocket Initialization Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.AsyncWebSocket.html Initializes the AsyncWebSocket client. You can specify the WebSocket server URL and whether to enable verbose output. ```APIDOC ## AsyncWebSocket ### Description Initializes the AsyncWebSocket client for streaming real-time pricing data. ### Parameters * **url** (_str_) - The WebSocket server URL. Defaults to Yahoo Finance’s WebSocket URL. * **verbose** (_bool_) - Flag to enable or disable print statements. Defaults to True. ``` -------------------------------- ### Get Financials Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Retrieves the financial statements for the ticker, either yearly or quarterly. ```APIDOC ## Get Financials ### Description Returns the financial statements for the ticker. ### Method get_financials ### Parameters * **as_dict** (bool) - Optional - If True, returns the table as a Python dictionary. Defaults to False. * **pretty** (bool) - Optional - If True, formats row names for readability. Defaults to False. * **freq** (str) - Optional - Specifies the frequency of the data, either 'yearly' or 'quarterly'. Defaults to 'yearly'. ``` -------------------------------- ### screen Source: https://ranaroussi.github.io/yfinance/reference/yfinance.screener.html Run a screen: predefined query, or custom query. ```APIDOC ## screen ### Description Run a screen using either a predefined query or a custom query. ### Method Signature `screen(query[, offset, size, count, ...])` ### Parameters - **query**: The query to run (predefined or custom). - **offset** (optional): The offset for the results. - **size** (optional): The number of results to return. - **count** (optional): The total count of results. ``` -------------------------------- ### Get Capital Gains Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Retrieves capital gains data for a specified period. ```APIDOC ## Get Capital Gains ### Description Returns capital gains for the ticker. ### Method get_capital_gains ### Parameters * **period** (str) - Optional - Defaults to 'max'. Specifies the period for which to retrieve capital gains. ``` -------------------------------- ### Initialize and Use Tickers Object Source: https://ranaroussi.github.io/yfinance/reference/yfinance.ticker_tickers.html Shows how to initialize a Tickers object for multiple stocks and access individual ticker data or perform actions across them. Includes accessing info, history, and actions for specific tickers, as well as live data. ```python 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 # websocket tickers.live() ``` -------------------------------- ### Run All Price Tests Source: https://ranaroussi.github.io/yfinance/development/testing.html Execute all tests within the `tests.test_prices` module. ```bash python -m unittest tests.test_prices ``` -------------------------------- ### Get Analyst Price Targets Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Fetches analyst price targets for the ticker. ```APIDOC ## Get Analyst Price Targets ### Description Returns a dictionary of analyst price targets. ### Method get_analyst_price_targets ### Returns dict: A dictionary with keys: current, low, high, mean, median. ``` -------------------------------- ### Get Income Statement Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Retrieves the income statement for the ticker, either yearly or quarterly. ```APIDOC ## Get Income Statement ### Description Returns the income statement for the ticker. ### Method get_income_stmt ### Parameters * **as_dict** (bool) - Optional - If True, returns the table as a Python dictionary. Defaults to False. * **pretty** (bool) - Optional - If True, formats row names for readability. Defaults to False. * **freq** (str) - Optional - Specifies the frequency of the data, 'yearly', 'quarterly', or 'trailing'. Defaults to 'yearly'. ``` -------------------------------- ### Asynchronous WebSocket Client with Context Manager Source: https://ranaroussi.github.io/yfinance/reference/yfinance.websocket.html Demonstrates the asynchronous WebSocket client using an async context manager to subscribe to price updates for AAPL and BTC-USD. Requires defining a message handler function and running within an async function. ```python import asyncio import yfinance as yf # define your message callback def message_handler(message): print("Received message:", message) async def main(): # ======================= # With Context Manager # ======================= async with yf.AsyncWebSocket() as ws: await ws.subscribe(["AAPL", "BTC-USD"]) await ws.listen() ``` -------------------------------- ### Get History Metadata Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Retrieves metadata related to historical price data for the ticker. ```APIDOC ## Get History Metadata ### Description Returns metadata related to historical price data. ### Method get_history_metadata ### Parameters * **repair** (object) - Optional - Default value depends on whether user requested price repair with a previous history() call. If not set here, it matches the previous history() call setting. ### Returns dict: Metadata dictionary. ``` -------------------------------- ### Tickers Initialization and Data Retrieval Source: https://ranaroussi.github.io/yfinance/reference/yfinance.ticker_tickers.html Shows how to initialize a Tickers object for multiple stocks and access their respective data, including general info, historical data, and actions. ```APIDOC ## Class Tickers ### Description Initializes Yahoo Finance Ticker objects for multiple stocks. ### Method Signature `Tickers(tickers[, session])` ### Usage Examples ```python import yfinance as yf # Initialize Tickers for multiple stocks tickers = yf.Tickers('msft aapl goog') # Access data for each ticker print(tickers.tickers['MSFT'].info) print(tickers.tickers['AAPL'].history(period="1mo")) print(tickers.tickers['GOOG'].actions) # websocket # print(tickers.live()) ``` ``` -------------------------------- ### Get EPS Trend Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Retrieves the earnings per share (EPS) trend for the ticker. ```APIDOC ## Get EPS Trend ### Description Returns the earnings per share (EPS) trend for the ticker. ### Method get_eps_trend ### Parameters * **as_dict** (bool) - Optional - If True, returns the data as a Python dictionary. Defaults to False. ### Returns DataFrame or dict: Data indexed by quarter/year with columns like current, 7daysAgo, 30daysAgo, 60daysAgo, 90daysAgo. ``` -------------------------------- ### Synchronous WebSocket Client with Context Manager Source: https://ranaroussi.github.io/yfinance/reference/yfinance.websocket.html Demonstrates how to use the synchronous WebSocket client with a context manager to subscribe to price updates for AAPL and BTC-USD. Requires defining a message handler function. ```python import yfinance as yf # define your message callback def message_handler(message): print("Received message:", message) # ======================= # With Context Manager # ======================= with yf.WebSocket() as ws: ws.subscribe(["AAPL", "BTC-USD"]) ws.listen(message_handler) ``` -------------------------------- ### Get Earnings Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Retrieves earnings data for the ticker, either yearly, quarterly, or trailing. ```APIDOC ## Get Earnings ### Description Returns earnings for the ticker. ### Method get_earnings ### Parameters * **as_dict** (bool) - Optional - If True, returns the table as a Python dictionary. Defaults to False. * **freq** (str) - Optional - Specifies the frequency of the data, 'yearly', 'quarterly', or 'trailing'. Defaults to 'yearly'. ``` -------------------------------- ### Ticker Initialization and Data Retrieval Source: https://ranaroussi.github.io/yfinance/reference/yfinance.ticker_tickers.html Demonstrates how to initialize a Ticker object for a single stock and access various financial data such as historical data, options, financials, calendar information, analyst targets, and live data. ```APIDOC ## Class Ticker ### Description Initializes a Yahoo Finance Ticker object for a single stock. ### Method Signature `Ticker(ticker[, session])` ### Usage Examples ```python import yfinance as yf dat = yf.Ticker("MSFT") # get historical market data print(dat.history(period='1mo')) # options print(dat.option_chain(dat.options[0]).calls) # get financials print(dat.balance_sheet) print(dat.quarterly_income_stmt) # dates print(dat.calendar) # general info print(dat.info) # analysis print(dat.analyst_price_targets) # websocket # print(dat.live()) ``` ``` -------------------------------- ### Get Actions Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Retrieves stock actions (e.g., splits, dividends) for a specified period. ```APIDOC ## Get Actions ### Description Returns stock actions for the ticker. ### Method get_actions ### Parameters * **period** (str) - Optional - Defaults to 'max'. Specifies the period for which to retrieve actions. ### Returns Series: A pandas Series containing the stock actions. ``` -------------------------------- ### General unittest Command Source: https://ranaroussi.github.io/yfinance/development/testing.html A general command structure for running tests, allowing specification of file, class, and method. ```bash python -m unittest tests.{file}.{class}.{method} ``` -------------------------------- ### Sector Initialization Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Sector.html Initializes a Sector object with a key and optional session and region. ```APIDOC ## Sector ### Description Initializes a Sector object. ### Method __init__ ### Parameters #### Path Parameters * **key** (str) - Required - The key representing the sector. * **session** (requests.Session) - Optional - A session for making requests. Defaults to None. * **region** (str) - Optional - Yahoo region (ISO 3166-1 alpha-2 country code, e.g. “US”, “GB”, “FR”, “DE”, “JP”). Scopes `top_companies`, `top_etfs` and `top_mutual_funds`. Defaults to “US”. ``` -------------------------------- ### Get Insider Roster Holders Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Retrieves a list of major holders among company insiders. ```APIDOC ## Get Insider Roster Holders ### Description Returns a list of major holders among company insiders. ### Method get_insider_roster_holders ### Parameters * **as_dict** (bool) - Optional - If True, returns the data as a Python dictionary. Defaults to False. ``` -------------------------------- ### Get EPS Revisions Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Retrieves earnings per share (EPS) revision data for the ticker. ```APIDOC ## Get EPS Revisions ### Description Returns earnings per share (EPS) revision data for the ticker. ### Method get_eps_revisions ### Parameters * **as_dict** (bool) - Optional - If True, returns the data as a Python dictionary. Defaults to False. ### Returns DataFrame or dict: Data indexed by quarter/year with columns like upLast7days, upLast30days, downLast7days, downLast30days. ``` -------------------------------- ### AsyncWebSocket Class Source: https://ranaroussi.github.io/yfinance/reference/index.html Enables asynchronous streaming of live market data. ```APIDOC ## AsyncWebSocket Class ### Description Class for asynchronously streaming live market data. ### Usage ```python import yfinance as yf async_ws = yf.AsyncWebSocket() # Usage details for asynchronous streaming would follow here. ``` ``` -------------------------------- ### Get Cash Flow Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Retrieves the cash flow statement for the ticker, either yearly or quarterly. ```APIDOC ## Get Cash Flow ### Description Returns the cash flow statement for the ticker. ### Method get_cash_flow ### Parameters * **as_dict** (bool) - Optional - If True, returns the table as a Python dictionary. Defaults to False. * **pretty** (bool) - Optional - If True, formats row names for readability. Defaults to False. * **freq** (str) - Optional - Specifies the frequency of the data, either 'yearly' or 'quarterly'. Defaults to 'yearly'. ``` -------------------------------- ### Get Balance Sheet Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Ticker.html Retrieves the balance sheet data for the ticker, either yearly or quarterly. ```APIDOC ## Get Balance Sheet ### Description Returns the balance sheet for the ticker. ### Method get_balance_sheet ### Parameters * **as_dict** (bool) - Optional - If True, returns the table as a Python dictionary. Defaults to False. * **pretty** (bool) - Optional - If True, formats row names for readability. Defaults to False. * **freq** (str) - Optional - Specifies the frequency of the data, either 'yearly' or 'quarterly'. Defaults to 'yearly'. ``` -------------------------------- ### get_shares_full Source: https://ranaroussi.github.io/yfinance/reference/yfinance.stock.html Retrieves the full history of shares outstanding for the stock, including start and end dates. ```APIDOC ## get_shares_full ### Description Retrieves the full history of shares outstanding for the stock, including start and end dates. ### Method ``` stock.get_shares_full(start=None, end=None) ``` ### Parameters #### Query Parameters - **start** (str or datetime) - Optional - The start date for the period. - **end** (str or datetime) - Optional - The end date for the period. ``` -------------------------------- ### Run a Predefined Screen Query Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.screen.html Use this snippet to execute a predefined stock screening query by its name. Ensure yfinance is imported. ```python import yfinance as yf response = yf.screen("aggressive_small_caps") ``` -------------------------------- ### Commit with Short Summary and Full Message Source: https://ranaroussi.github.io/yfinance/development/code.html Format your commit messages with a concise summary on the first line, followed by a more detailed explanation on subsequent lines. This helps keep the commit history clean. ```bash git commit -m "short sentence summary" -m "full commit message" # Long message can be multiple lines (tip: copy-paste) ``` -------------------------------- ### Setting Locale for Translated Fields (Japan) Source: https://ranaroussi.github.io/yfinance/advanced/config.html Configure the language and region for localized fields. This example sets it to Japanese for Japan. ```python import yfinance as yf yf.config.locale.lang = "ja-JP" yf.config.locale.region = "JP" yf.Ticker("7203.T").info["longName"] # → 'トヨタ自動車' ``` -------------------------------- ### Dividend Too Big Example Source: https://ranaroussi.github.io/yfinance/advanced/price_repair.html Illustrates a situation where the dividend amount is excessively large compared to the price drop. The dividend value is corrected. ```python # ORIGINAL: Close Adj Close Dividends 2024-06-27 00:00:00+01:00 2.360 2.3600 1.78 2024-06-26 00:00:00+01:00 2.375 2.3572 0.00 ``` ```python # REPAIRED: Close Adj Close Dividends 2024-06-27 00:00:00+01:00 2.360 2.3600 0.0178 2024-06-26 00:00:00+01:00 2.375 2.3572 0.0000 ``` -------------------------------- ### Access Fund Data with Ticker Source: https://ranaroussi.github.io/yfinance/reference/yfinance.ticker_tickers.html Demonstrates how to retrieve and access fund-specific data for ETFs or Mutual Funds using the Ticker object, including descriptions, operational details, and holdings. ```python import yfinance as yf spy = yf.Ticker('SPY') data = spy.funds_data # show fund description data.description # show operational information data.fund_overview data.fund_operations # show holdings related information data.asset_classes data.top_holdings data.equity_holdings data.bond_holdings data.bond_ratings data.sector_weightings ``` -------------------------------- ### ETFQuery Initialization Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.ETFQuery.html Initializes an ETFQuery object with a specified operator and a list of operands. The operator determines the type of comparison, and operands are the values to compare against. Supported operators include 'eq', 'is-in', 'btwn', 'gt', 'lt', 'gte', 'lte', 'and', 'or'. Operands can be lists of strings or real numbers. ```python ETFQuery(operator='eq', operand=['ETF1', 'ETF2']) ETFQuery(operator='is-in', operand=['ETF1', 'ETF2']) ETFQuery(operator='btwn', operand=[10, 20]) ETFQuery(operator='gt', operand=[10]) ETFQuery(operator='lt', operand=[20]) ETFQuery(operator='gte', operand=[15]) ETFQuery(operator='lte', operand=[25]) ETFQuery(operator='and', operand=[ETFQuery('eq', ['ETF1']), ETFQuery('gt', [10])]) ETFQuery(operator='or', operand=[ETFQuery('eq', ['ETF1']), ETFQuery('gt', [10])]) ``` -------------------------------- ### Setting Network Proxy Source: https://ranaroussi.github.io/yfinance/advanced/config.html Configure a proxy server for all yfinance data fetches. Replace 'PROXY_SERVER' with your actual proxy address. ```python yf.config.network.proxy = "PROXY_SERVER" ``` -------------------------------- ### Lookup Module - Get All Source: https://ranaroussi.github.io/yfinance/reference/yfinance.search.html Retrieves all types of financial instruments associated with a ticker symbol using the Lookup module. Requires importing the yfinance library. ```python import yfinance as yf # Get All all = yf.Lookup("AAPL").all all = yf.Lookup("AAPL").get_all(count=100) ``` -------------------------------- ### config.debug.logging Source: https://ranaroussi.github.io/yfinance/reference/index.html Enable verbose debug logging for the yfinance package. ```APIDOC ## config.debug.logging ### Description Enable verbose debug logging. ### Usage ```python import yfinance as yf yf.config.debug.logging = True ``` ``` -------------------------------- ### Applying nest_asyncio for Jupyter Notebooks Source: https://ranaroussi.github.io/yfinance/reference/yfinance.websocket.html Provides the necessary code to apply the nest_asyncio library, which is required to resolve event loop issues when running asynchronous code within a Jupyter notebook environment. ```python import nest_asyncio nest_asyncio.apply() ``` -------------------------------- ### Lookup Module - Get Currencies Source: https://ranaroussi.github.io/yfinance/reference/yfinance.search.html Retrieves a list of currency instruments for a specified ticker symbol using the Lookup module. Requires importing the yfinance library. ```python import yfinance as yf # Get Currencies currency = yf.Lookup("AAPL").currency currency = yf.Lookup("AAPL").get_currency(count=100) ``` -------------------------------- ### Lookup Module - Get Futures Source: https://ranaroussi.github.io/yfinance/reference/yfinance.search.html Fetches a list of futures instruments for a given ticker symbol using the Lookup module. Requires importing the yfinance library. ```python import yfinance as yf # Get Futures future = yf.Lookup("AAPL").future future = yf.Lookup("AAPL").get_future(count=100) ``` -------------------------------- ### EquityQuery Constructor Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.EquityQuery.html Constructs filters for stocks based on specific criteria. Supports value operations like EQ, IS-IN, BTWN, GT, LT, GTE, LTE, and logical operations like AND, OR. ```APIDOC ## EquityQuery Constructor ### Description Initializes an EquityQuery object to build stock filters. It takes an operator (e.g., 'eq', 'is-in', 'and') and a list of operands. ### Parameters * `_operator`: Literal['eq', 'is-in', 'btwn', 'gt', 'lt', 'gte', 'lte', 'and', 'or'] - The type of operation to perform. * `_operand`: List[QueryBase] | List[str] | List[Real] - The values or nested queries to apply to the operator. ### Example ```python from yfinance import EquityQuery EquityQuery('and', [ EquityQuery('is-in', ['exchange', 'NMS', 'NYQ']), EquityQuery('lt', ['epsgrowth.lasttwelvemonths', 15]) ]) ``` ```