### Install yfinance Source: https://ranaroussi.github.io/yfinance/_sources/index.rst.txt Install the yfinance library using pip. ```bash pip install yfinance ``` -------------------------------- ### Search Module Example Source: https://ranaroussi.github.io/yfinance/_sources/reference/yfinance.search.rst.txt Demonstrates how to use the Search module to access search data. Ensure the 'search.py' file is available in the examples directory. ```python from yfinance import Search search = Search() # Example: Search for companies related to 'technology' results = search.companies(query='technology') print(results) # Example: Search for ETFs related to 'bonds' results = search.etfs(query='bonds') print(results) # Example: Search for mutual funds related to 'growth' results = search.mutualfunds(query='growth') print(results) ``` -------------------------------- ### Install Documentation Dependencies Source: https://ranaroussi.github.io/yfinance/_sources/development/documentation.rst.txt Installs Sphinx and other necessary packages for building documentation. Ensure you have a requirements.txt file. ```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 ``` -------------------------------- ### Market Class Usage Example Source: https://ranaroussi.github.io/yfinance/_sources/reference/yfinance.market.rst.txt Demonstrates how to use the Market class to access market data. This snippet requires the yfinance library to be installed. ```python from yfinance import Market market = Market() # Get summary data for all markets s = market.summary print(s) # Get status for US market s = market.status("US") print(s) # Get status for non-US market (will return None and log a warning) s = market.status("GB") print(s) ``` -------------------------------- ### Install yfinance from a specific branch using pip Source: https://ranaroussi.github.io/yfinance/_sources/development/running.rst.txt Use this command to install yfinance directly from a Git branch. Replace `{user}` and `{repo}` with the appropriate GitHub username and repository name, and `{branch}` with the target branch name. ```bash pip install git+https://github.com/{user}/{repo}.git@{branch} ``` ```bash pip install git+https://github.com/ranaroussi/yfinance.git@feature/name ``` -------------------------------- ### Serve Local Documentation Source: https://ranaroussi.github.io/yfinance/_sources/development/documentation.rst.txt Starts a local HTTP server to view the generated HTML documentation. Navigate to localhost:8000 in your browser. ```bash python -m http.server -d ./doc/_build/html ``` -------------------------------- ### Verify yfinance installation Source: https://ranaroussi.github.io/yfinance/_sources/development/running.rst.txt Import and print the yfinance module to verify that it has been correctly installed or added to the Python path. The output should indicate the location of the imported module. ```python import yfinance print(yfinance) ``` -------------------------------- ### Tickers.live Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Tickers.html Starts a live data stream for the specified tickers. ```APIDOC ## Tickers.live ### Description Starts a live data stream for the tickers associated with the Tickers object. ### Parameters - **_message_handler_** (callable, optional) - A function to call when a new message is received. - **_verbose_** (bool, optional) - Whether to print live data to the console. Defaults to True. ``` -------------------------------- ### Get Earnings Calendar with Default Parameters Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Calendars.html Instantiate the Calendars class and retrieve the earnings calendar with default settings. This example shows the basic usage for fetching earnings data. ```python import yfinance as yf calendars = yf.Calendars() earnings_calendar = calendars.get_earnings_calendar(limit=50) print(earnings_calendar) ``` -------------------------------- ### Clone yfinance repository and install dependencies Source: https://ranaroussi.github.io/yfinance/_sources/development/running.rst.txt Clone the yfinance repository and install its dependencies. Use the `-b {branch}` flag to clone a specific branch. This method is suitable for development or when testing changes on a particular branch. ```bash git clone https://github.com/{user}/{repo}.git pip install -r ./yfinance/requirements.txt ``` ```bash git clone -b {branch} https://github.com/{user}/{repo}.git pip install -r ./yfinance/requirements.txt ``` -------------------------------- ### Install yfinance without curl_cffi Source: https://ranaroussi.github.io/yfinance/_sources/advanced/install.rst.txt Use this command to install yfinance while excluding 'curl_cffi' from the requirements, ensuring a requests fallback. This installs dependencies from stdin and then yfinance without its own dependencies. ```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 ``` -------------------------------- ### Initialize Sector and Industry Modules Source: https://ranaroussi.github.io/yfinance/_sources/reference/yfinance.sector_industry.rst.txt Initialize the Sector and Industry modules using their respective keys. This is the basic setup for accessing sector and industry information. ```python import yfinance as yf # Initialize Sector and Industry modules sector_info = yf.Sector("technology") industry_info = yf.Industry("software-infrastructure") print(sector_info.info) print(industry_info.info) ``` -------------------------------- ### Initialize Market and Access Data Source: https://ranaroussi.github.io/yfinance/reference/yfinance.market.html Demonstrates how to initialize a Market object for Europe and access its status and summary attributes. Requires the yfinance library to be installed. ```python import yfinance as yf EUROPE = yf.Market("EUROPE") status = EUROPE.status summary = EUROPE.summary ``` -------------------------------- ### Use Proxy Server for Data Download Source: https://ranaroussi.github.io/yfinance/reference/yfinance.ticker_tickers.html Provides an example of how to configure a proxy server for downloading various types of financial data using the Ticker object. ```python import 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") ... ``` -------------------------------- ### Run All Price Tests Source: https://ranaroussi.github.io/yfinance/_sources/development/testing.rst.txt Execute all tests located within the `tests.test_prices` module. Ensure you have the unittest module installed and accessible. ```bash python -m unittest tests.test_prices ``` -------------------------------- ### Get Upcoming Earnings Events with yfinance Calendars Source: https://ranaroussi.github.io/yfinance/_sources/reference/yfinance.calendars.rst.txt Use the Calendars class to fetch upcoming earnings events. Ensure yfinance is installed and imported. ```python import yfinance as yf # Get upcoming earnings events earnings = yf.Actions.earnings print(earnings) # Get upcoming dividend events dividends = yf.Actions.dividends print(dividends) # Get upcoming stock splits events splits = yf.Actions.stock_splits print(splits) ``` -------------------------------- ### Python Authentication Example Source: https://ranaroussi.github.io/yfinance/_sources/reference/yfinance.auth.rst.txt This snippet demonstrates how to use the Auth module to log in to Yahoo! Finance by providing authentication cookies. ```python from yfinance.auth import Auth # Replace with your actual cookie values cookie_t = "YOUR_T_COOKIE_VALUE" cookie_y = "YOUR_Y_COOKIE_VALUE" # Create an Auth object auth = Auth(cookie_t, cookie_y) # You can now use this auth object with yfinance functions that require authentication # For example: # import yfinance as yf # ticker = yf.Ticker("AAPL", session=auth.session) # print(ticker.history(period="1d")) print("Authentication object created successfully.") ``` -------------------------------- ### Example Usage of FundQuery Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.FundQuery.html Demonstrates how to construct a complex filter for mutual funds using the FundQuery class, combining multiple criteria with logical operators. ```APIDOC ## Example Predefined Yahoo query solid_large_growth_funds: ```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']) ]) ``` ``` -------------------------------- ### AsyncWebSocket.listen() Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.AsyncWebSocket.html Starts listening for messages from the WebSocket server and optionally processes them with a handler. ```APIDOC ## AsyncWebSocket.listen() ### Description Starts listening to messages from the WebSocket server. You can provide a callback function to handle incoming messages. ### Parameters * **message_handler** (_Optional[Callable[[dict], None]]_) - Optional function to handle received messages. This function will be called with a dictionary representing the message. ``` -------------------------------- ### Lookup Module Example Source: https://ranaroussi.github.io/yfinance/_sources/reference/yfinance.search.rst.txt Illustrates how to use the Lookup module for ticker symbol retrieval. This code requires the 'lookup.py' file to be present. ```python from yfinance import Lookup lookup = Lookup() # Example: Look up tickers for 'Apple Inc.' results = lookup.by_company_name('Apple Inc.') print(results) # Example: Look up tickers by sector 'Technology' results = lookup.by_sector('Technology') print(results) # Example: Look up tickers by industry 'Semiconductors' results = lookup.by_industry('Semiconductors') print(results) ``` -------------------------------- ### ETFQuery Example Usage Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.ETFQuery.html Demonstrates how to use the ETFQuery class to build a filter for US ETFs with a performance rating of 4 or 5 and an intraday price greater than 10. ```APIDOC ### Example ```python from yfinance import ETFQuery ETFQuery('and', [ ETFQuery('gt', ['intradayprice', 10]), ETFQuery('is-in', ['performanceratingoverall', 4, 5]), ETFQuery('eq', ['region', 'us']) ]) ``` ``` -------------------------------- ### WebSocket.listen() Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.WebSocket.html Starts listening for messages from the WebSocket server. A message handler can be provided to process incoming data. ```APIDOC ## WebSocket.listen() ### Description Start listening to messages from the WebSocket server. ### Parameters - **message_handler** (Callable[[dict], None] | None) - Optional function to handle received messages. ``` -------------------------------- ### Run a custom stock screen query Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.screen.html Construct and execute a custom stock screening query using EquityQuery. This example filters for stocks with a percentage change greater than 3% and in the 'us' region, then sorts by percentage 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) ``` -------------------------------- ### Initialize Calendars Object Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Calendars.html Instantiate the Calendars object, optionally providing start and end dates, and a requests.Session object. ```APIDOC ## Initialize Calendars ### Description Instantiates the Calendars object to access financial calendar data. ### Method Signature __init__(self, start : str | datetime | date | None = None, end : str | datetime | date | None = None, session : Session | None = None) ### Parameters #### Parameters - **start** (_str_ | _datetime_ | _date_) – start date (default today) eg. start=”2025-11-08” - **end** (_str_ | _datetime_ | _date_) – end date (default start + 7 days) eg. end=”2025-11-08” - **session** – requests.Session object, optional ``` -------------------------------- ### Asynchronous WebSocket Client Source: https://ranaroussi.github.io/yfinance/reference/yfinance.websocket.html Illustrates the use of the asynchronous WebSocket client for streaming price data. Includes examples with and without a context manager, suitable for asynchronous applications. ```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() # ======================= # Without Context Manager # ======================= ws = yf.AsyncWebSocket() await ws.subscribe(["AAPL", "BTC-USD"]) await ws.listen() asyncio.run(main()) ``` -------------------------------- ### Constructing a Stock Filter with EquityQuery Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.EquityQuery.html Use EquityQuery to build filters for stocks. This example filters for stocks in the 'NMS' or 'NYQ' exchanges with an EPS growth of less than 15%. ```python from yfinance import EquityQuery EquityQuery('and', [ EquityQuery('is-in', ['exchange', 'NMS', 'NYQ']), EquityQuery('lt', ["epsgrowth.lasttwelvemonths", 15]) ]) ``` -------------------------------- ### Initialize Ticker Object Source: https://ranaroussi.github.io/yfinance/_sources/reference/yfinance.ticker_tickers.rst.txt Access individual ticker data using the Ticker module. No specific setup is required beyond importing the library. ```python import yfinance as yf ticker = yf.Ticker("AAPL") # Access historical data hist = ticker.history(period="1mo") print(hist.head()) # Access info data info = ticker.info print(info) # Access options data options = ticker.options print(options) # Access institutional holders institutional_holders = ticker.institutional_holders print(institutional_holders) # Access major holders major_holders = ticker.major_holders print(major_holders) # Access corporate actions corporate_actions = ticker.corporate_actions print(corporate_actions) # Access sustainability data sustainability = ticker.sustainability print(sustainability) # Access recommendations recommendations = ticker.recommendations print(recommendations) # Access next earnings date next_earnings_date = ticker.next_earnings_date print(next_earnings_date) # Access shares outstanding shares_outstanding = ticker.shares_outstanding print(shares_outstanding) # Access shares float shares_float = ticker.shares_float print(shares_float) # Access beta beta = ticker.beta print(beta) # Access forward PE ratios forward_pe = ticker.forward_pe print(forward_pe) # Access dividend rate dividend_rate = ticker.dividend_rate print(dividend_rate) # Access dividend yield dividend_yield = ticker.dividend_yield print(dividend_yield) # Access ex-dividend date ex_dividend_date = ticker.ex_dividend_date print(ex_dividend_date) # Access P/E ratio pe_ratio = ticker.pe_ratio print(pe_ratio) # Access 52 week high high_52_week = ticker.high_52_week print(high_52_week) # Access 52 week low low_52_week = ticker.low_52_week print(low_52_week) # Access market cap market_cap = ticker.market_cap print(market_cap) # Access volume volume = ticker.volume print(volume) # Access average volume average_volume = ticker.average_volume print(average_volume) # Access previous close price previous_close = ticker.previous_close print(previous_close) # Access open price open_price = ticker.open print(open_price) # Access day low price day_low = ticker.day_low print(day_low) # Access day high price day_high = ticker.day_high print(day_high) # Access regular market previous close price regular_market_previous_close = ticker.regular_market_previous_close print(regular_market_previous_close) # Access regular market open price regular_market_open = ticker.regular_market_open print(regular_market_open) # Access regular market day low price regular_market_day_low = ticker.regular_market_day_low print(regular_market_day_low) # Access regular market day high price regular_market_day_high = ticker.regular_market_day_high print(regular_market_day_high) # Access two hundred day average price two_hundred_day_average = ticker.two_hundred_day_average print(two_hundred_day_average) # Access three month average volume three_month_average_volume = ticker.three_month_average_volume print(three_month_average_volume) # Access five year average return five_year_average_return = ticker.five_year_average_return print(five_year_average_return) # Access beta three year average beta_three_year_average = ticker.beta_three_year_average print(beta_three_year_average) # Access profit margin profit_margin = ticker.profit_margin print(profit_margin) # Access operating margin operating_margin = ticker.operating_margin print(operating_margin) # Access return on assets return_on_assets = ticker.return_on_assets print(return_on_assets) # Access return on equity return_on_equity = ticker.return_on_equity print(return_on_equity) # Access earnings quarterly growth earnings_quarterly_growth = ticker.earnings_quarterly_growth print(earnings_quarterly_growth) # Access revenue quarterly growth revenue_quarterly_growth = ticker.revenue_quarterly_growth print(revenue_quarterly_growth) # Access net income to common net_income_to_common = ticker.net_income_to_common print(net_income_to_common) # Access basic eps basic_eps = ticker.basic_eps print(basic_eps) # Access diluted eps diluted_eps = ticker.diluted_eps print(diluted_eps) # Access earnings before interest and taxes earnings_before_interest_and_taxes = ticker.earnings_before_interest_and_taxes print(earnings_before_interest_and_taxes) # Access earnings before tax earnings_before_tax = ticker.earnings_before_tax print(earnings_before_tax) # Access diluted net income diluted_net_income = ticker.diluted_net_income print(diluted_net_income) # Access net income from continuing and discontinued operation net_income_from_continuing_and_discontinued_operation = ticker.net_income_from_continuing_and_discontinued_operation print(net_income_from_continuing_and_discontinued_operation) # Access total revenue total_revenue = ticker.total_revenue print(total_revenue) # Access gross profit gross_profit = ticker.gross_profit print(gross_profit) # Access operating income operating_income = ticker.operating_income print(operating_income) # Access selling general and administrative expense selling_general_and_administrative_expense = ticker.selling_general_and_administrative_expense print(selling_general_and_administrative_expense) # Access research and development expense research_and_development_expense = ticker.research_and_development_expense print(research_and_development_expense) # Access cost of revenue cost_of_revenue = ticker.cost_of_revenue print(cost_of_revenue) # Access total operating expenses total_operating_expenses = ticker.total_operating_expenses print(total_operating_expenses) # Access interest expense interest_expense = ticker.interest_expense print(interest_expense) # Access depreciation and amortization depreciation_and_amortization = ticker.depreciation_and_amortization print(depreciation_and_amortization) # Access stock based compensation stock_based_compensation = ticker.stock_based_compensation print(stock_based_compensation) # Access other income expense net other_income_expense_net = ticker.other_income_expense_net print(other_income_expense_net) # Access income before tax income_before_tax = ticker.income_before_tax print(income_before_tax) # Access minority interest minority_interest = ticker.minority_interest print(minority_interest) # Access tax provision tax_provision = ticker.tax_provision print(tax_provision) # Access net income from continuing operation net_income_from_continuing_operation = ticker.net_income_from_continuing_operation print(net_income_from_continuing_operation) # Access diluted eps from continuing operation diluted_eps_from_continuing_operation = ticker.diluted_eps_from_continuing_operation print(diluted_eps_from_continuing_operation) # Access diluted normalized eps diluted_normalized_eps = ticker.diluted_normalized_eps print(diluted_normalized_eps) # Access total cash total_cash = ticker.total_cash print(total_cash) # Access short term debt short_term_debt = ticker.short_term_debt print(short_term_debt) # Access long term debt long_term_debt = ticker.long_term_debt print(long_term_debt) # Access total debt total_debt = ticker.total_debt print(total_debt) # Access current ratio current_ratio = ticker.current_ratio print(current_ratio) # Access quick ratio quick_ratio = ticker.quick_ratio print(quick_ratio) # Access cash flow from investment cash_flow_from_investment = ticker.cash_flow_from_investment print(cash_flow_from_investment) # Access cash flow from financing cash_flow_from_financing = ticker.cash_flow_from_financing print(cash_flow_from_financing) # Access net cash used provided by operating activities net_cash_used_provided_by_operating_activities = ticker.net_cash_used_provided_by_operating_activities print(net_cash_used_provided_by_operating_activities) # Access free cash flow free_cash_flow = ticker.free_cash_flow print(free_cash_flow) # Access dividends paid dividends_paid = ticker.dividends_paid print(dividends_paid) # Access stock repurchase stock_repurchase = ticker.stock_repurchase print(stock_repurchase) # Access capital expenditures capital_expenditures = ticker.capital_expenditures print(capital_expenditures) # Access share statistics share_statistics = ticker.share_statistics print(share_statistics) # Access earnings history earnings_history = ticker.earnings_history print(earnings_history) # Access dividends history dividends_history = ticker.dividends_history print(dividends_history) # Access financial data financial_data = ticker.financial_data print(financial_data) # Access balance sheet data balance_sheet_data = ticker.balance_sheet_data print(balance_sheet_data) # Access cash flow data cash_flow_data = ticker.cash_flow_data print(cash_flow_data) # Access income statement data income_statement_data = ticker.income_statement_data print(income_statement_data) # Access news news = ticker.news print(news) # Access analyst recommendations analyst_recommendations = ticker.analyst_recommendations print(analyst_recommendations) # Access earnings forecast earnings_forecast = ticker.earnings_forecast print(earnings_forecast) # Access revenue forecast revenue_forecast = ticker.revenue_forecast print(revenue_forecast) # Access index patents index_patents = ticker.index_patents print(index_patents) # Access upgrades_downgrades upgrades_downgrades = ticker.upgrades_downgrades print(upgrades_downgrades) # Access shares shares = ticker.shares print(shares) # Access mutual fund information mutual_fund_information = ticker.mutual_fund_information print(mutual_fund_information) # Access etf information etf_information = ticker.etf_information print(etf_information) # Access sector performance sector_performance = ticker.sector_performance print(sector_performance) # Access mutual fund performance mutual_fund_performance = ticker.mutual_fund_performance print(mutual_fund_performance) # Access etf performance etf_performance = ticker.etf_performance print(etf_performance) # Access mutual fund country exposure mutual_fund_country_exposure = ticker.mutual_fund_country_exposure print(mutual_fund_country_exposure) # Access etf country exposure etf_country_exposure = ticker.etf_country_exposure print(etf_country_exposure) # Access mutual fund asset turnover mutual_fund_asset_turnover = ticker.mutual_fund_asset_turnover print(mutual_fund_asset_turnover) # Access etf asset turnover etf_asset_turnover = ticker.etf_asset_turnover print(etf_asset_turnover) # Access mutual fund fees expenses ratios mutual_fund_fees_expenses_ratios = ticker.mutual_fund_fees_expenses_ratios print(mutual_fund_fees_expenses_ratios) # Access etf fees expenses ratios etf_fees_expenses_ratios = ticker.etf_fees_expenses_ratios print(etf_fees_expenses_ratios) # Access mutual fund holdings mutual_fund_holdings = ticker.mutual_fund_holdings print(mutual_fund_holdings) # Access etf holdings etf_holdings = ticker.etf_holdings print(etf_holdings) # Access mutual fund top holdings mutual_fund_top_holdings = ticker.mutual_fund_top_holdings print(mutual_fund_top_holdings) # Access etf top holdings etf_top_holdings = ticker.etf_top_holdings print(etf_top_holdings) # Access mutual fund top instruments mutual_fund_top_instruments = ticker.mutual_fund_top_instruments print(mutual_fund_top_instruments) # Access etf top instruments etf_top_instruments = ticker.etf_top_instruments print(etf_top_instruments) # Access mutual fund top countries mutual_fund_top_countries = ticker.mutual_fund_top_countries print(mutual_fund_top_countries) # Access etf top countries etf_top_countries = ticker.etf_top_countries print(etf_top_countries) # Access mutual fund top sectors mutual_fund_top_sectors = ticker.mutual_fund_top_sectors print(mutual_fund_top_sectors) # Access etf top sectors etf_top_sectors = ticker.etf_top_sectors print(etf_top_sectors) # Access mutual fund top industries mutual_fund_top_industries = ticker.mutual_fund_top_industries print(mutual_fund_top_industries) # Access etf top industries etf_top_industries = ticker.etf_top_industries print(etf_top_industries) # Access mutual fund top issuers mutual_fund_top_issuers = ticker.mutual_fund_top_issuers print(mutual_fund_top_issuers) # Access etf top issuers etf_top_issuers = ticker.etf_top_issuers print(etf_top_issuers) # Access mutual fund top issuers in country mutual_fund_top_issuers_in_country = ticker.mutual_fund_top_issuers_in_country print(mutual_fund_top_issuers_in_country) # Access etf top issuers in country etf_top_issuers_in_country = ticker.etf_top_issuers_in_country print(etf_top_issuers_in_country) # Access mutual fund top issuers in industry mutual_fund_top_issuers_in_industry = ticker.mutual_fund_top_issuers_in_industry print(mutual_fund_top_issuers_in_industry) # Access etf top issuers in industry etf_top_issuers_in_industry = ticker.etf_top_issuers_in_industry print(etf_top_issuers_in_industry) # Access mutual fund top issuers in sector mutual_fund_top_issuers_in_sector = ticker.mutual_fund_top_issuers_in_sector print(mutual_fund_top_issuers_in_sector) # Access etf top issuers in sector etf_top_issuers_in_sector = ticker.etf_top_issuers_in_sector print(etf_top_issuers_in_sector) # Access mutual fund top issuers in country of domicile mutual_fund_top_issuers_in_country_of_domicile = ticker.mutual_fund_top_issuers_in_country_of_domicile print(mutual_fund_top_issuers_in_country_of_domicile) # Access etf top issuers in country of domicile etf_top_issuers_in_country_of_domicile = ticker.etf_top_issuers_in_country_of_domicile print(etf_top_issuers_in_country_of_domicile) # Access mutual fund top issuers in industry of domicile mutual_fund_top_issuers_in_industry_of_domicile = ticker.mutual_fund_top_issuers_in_industry_of_domicile print(mutual_fund_top_issuers_in_industry_of_domicile) # Access etf top issuers in industry of domicile etf_top_issuers_in_industry_of_domicile = ticker.etf_top_issuers_in_industry_of_domicile print(etf_top_issuers_in_industry_of_domicile) # Access mutual fund top issuers in sector of domicile mutual_fund_top_issuers_in_sector_of_domicile = ticker.mutual_fund_top_issuers_in_sector_of_domicile print(mutual_fund_top_issuers_in_sector_of_domicile) # Access etf top issuers in sector of domicile etf_top_issuers_in_sector_of_domicile = ticker.etf_top_issuers_in_sector_of_domicile print(etf_top_issuers_in_sector_of_domicile) # Access mutual fund top issuers in country of domicile and industry mutual_fund_top_issuers_in_country_of_domicile_and_industry = ticker.mutual_fund_top_issuers_in_country_of_domicile_and_industry print(mutual_fund_top_issuers_in_country_of_domicile_and_industry) # Access etf top issuers in country of domicile and industry etf_top_issuers_in_country_of_domicile_and_industry = ticker.etf_top_issuers_in_country_of_domicile_and_industry print(etf_top_issuers_in_country_of_domicile_and_industry) # Access mutual fund top issuers in country of domicile and sector mutual_fund_top_issuers_in_country_of_domicile_and_sector = ticker.mutual_fund_top_issuers_in_country_of_domicile_and_sector print(mutual_fund_top_issuers_in_country_of_domicile_and_sector) # Access etf top issuers in country of domicile and sector etf_top_issuers_in_country_of_domicile_and_sector = ticker.etf_top_issuers_in_country_of_domicile_and_sector print(etf_top_issuers_in_country_of_domicile_and_sector) # Access mutual fund top issuers in industry of domicile and sector mutual_fund_top_issuers_in_industry_of_domicile_and_sector = ticker.mutual_fund_top_issuers_in_industry_of_domicile_and_sector print(mutual_fund_top_issuers_in_industry_of_domicile_and_sector) # Access etf top issuers in industry of domicile and sector etf_top_issuers_in_industry_of_domicile_and_sector = ticker.etf_top_issuers_in_industry_of_domicile_and_sector print(etf_top_issuers_in_industry_of_domicile_and_sector) # Access mutual fund top issuers in country of domicile and industry and sector mutual_fund_top_issuers_in_country_of_domicile_and_industry_and_sector = ticker.mutual_fund_top_issuers_in_country_of_domicile_and_industry_and_sector print(mutual_fund_top_issuers_in_country_of_domicile_and_industry_and_sector) # Access etf top issuers in country of domicile and industry and sector etf_top_issuers_in_country_of_domicile_and_industry_and_sector = ticker.etf_top_issuers_in_country_of_domicile_and_industry_and_sector print(etf_top_issuers_in_country_of_domicile_and_industry_and_sector) ``` -------------------------------- ### Add local yfinance to Python path Source: https://ranaroussi.github.io/yfinance/_sources/development/running.rst.txt Add the downloaded yfinance directory to your Python path to allow imports. This is necessary if you are running yfinance from a local clone rather than an installed package. ```python import sys sys.path.insert(0, "path/to/downloaded/yfinance") ``` -------------------------------- ### Constructing ETF Filters with ETFQuery Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.ETFQuery.html Use ETFQuery to build filters for ETFs. Combine value operations like 'gt' and 'is-in' with logical operations like 'and' to specify criteria. This example filters for US ETFs with a performance rating of 4 or 5 and an intraday price greater than 10. ```python from yfinance import ETFQuery ETFQuery('and', [ ETFQuery('gt', ['intradayprice', 10]), ETFQuery('is-in', ['performanceratingoverall', 4, 5]), ETFQuery('eq', ['region', 'us']) ]) ``` -------------------------------- ### 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 and access common information 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 ``` -------------------------------- ### 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 with Ticker methods. ```APIDOC ## Proxy Server Configuration ### Description To use a proxy server for downloading data, you can specify the `proxy` argument in various Ticker methods. ### Usage Example ```python import yfinance as yf msft = yf.Ticker("MSFT") # Example using proxy for history data msft.history(period='1d', proxy="PROXY_SERVER") # Example using proxy for other data retrieval methods 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(msft.options[0], proxy="PROXY_SERVER") ``` ``` -------------------------------- ### Initialize and Query yfinance Calendars Source: https://ranaroussi.github.io/yfinance/reference/yfinance.calendars.html Demonstrates how to initialize the Calendars class with default settings or custom date ranges. Accessing properties like `earnings_calendar` fetches data, while `get_` methods allow for manual queries. ```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() ``` -------------------------------- ### Initialize and Use Ticker Object Source: https://ranaroussi.github.io/yfinance/reference/yfinance.ticker_tickers.html Demonstrates initializing a Ticker object for a single stock and accessing various data points like historical data, financials, options, and analyst information. ```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() ``` -------------------------------- ### 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] ``` -------------------------------- ### 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] ``` -------------------------------- ### Build Documentation Locally with Sphinx Source: https://ranaroussi.github.io/yfinance/development/documentation.html Generates HTML documentation from the Sphinx source files. The output is placed in the doc/_build/html directory. ```bash sphinx-build -b html doc/source doc/_build/html ``` -------------------------------- ### Get Stock Instruments Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Lookup.html Retrieves a DataFrame containing stocks related to the query. ```APIDOC ## get_stock() ### Description Returns stock related financial instruments. ### Parameters - **count** (int) – The number of results to retrieve (default 25). ### Returns DataFrame containing stock instruments. ``` -------------------------------- ### Get Index Instruments Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Lookup.html Retrieves a DataFrame containing indices related to the query. ```APIDOC ## get_index() ### Description Returns Indices related financial instruments. ### Parameters - **count** (int) – The number of results to retrieve (default 25). ### Returns DataFrame containing index instruments. ``` -------------------------------- ### Get Future Instruments Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Lookup.html Retrieves a DataFrame containing futures related to the query. ```APIDOC ## get_future() ### Description Returns Futures related financial instruments. ### Parameters - **count** (int) – The number of results to retrieve (default 25). ### Returns DataFrame containing future instruments. ``` -------------------------------- ### AsyncWebSocket Initialization Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.AsyncWebSocket.html Initializes the AsyncWebSocket client with an optional URL and verbosity setting. ```APIDOC ## AsyncWebSocket Initialization ### Description Initializes the AsyncWebSocket client. You can specify the WebSocket server URL and control print statements. ### Parameters * **url** (_str_) - Optional. The WebSocket server URL. Defaults to Yahoo Finance’s WebSocket URL. * **verbose** (_bool_) - Optional. Flag to enable or disable print statements. Defaults to True. ``` -------------------------------- ### Build HTML Documentation with Sphinx Source: https://ranaroussi.github.io/yfinance/_sources/development/documentation.rst.txt Generates HTML documentation from the Sphinx source files. The output will be placed in the specified build directory. ```bash sphinx-build -b html doc/source doc/_build/html ``` -------------------------------- ### Get ETF Instruments Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Lookup.html Retrieves a DataFrame containing ETFs related to the query. ```APIDOC ## get_etf() ### Description Returns ETFs related financial instruments. ### Parameters - **count** (int) – The number of results to retrieve (default 25). ### Returns DataFrame containing ETF instruments. ``` -------------------------------- ### Calendars Class Initialization and Usage Source: https://ranaroussi.github.io/yfinance/reference/yfinance.calendars.html Demonstrates how to initialize the Calendars class with default settings or custom date ranges, and how to access different event calendars. ```APIDOC ## Calendars Class The `Calendars` class allows you to get information about upcoming events, for example, earning events. `Calendars`([start, end, session]) | Get economic calendars, for example, Earnings, IPO, Economic Events, Splits ### Sample Code ```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() # Earnings calendar custom filters calendar.get_earnings_calendar( market_cap=100_000_000, # filter out small-cap filter_most_active=True, # show only actively traded. Uses: `screen(query="MOST_ACTIVES")` ) # Example of real use case: # Get inminent unreported earnings events today = datetime.now() is_friday = today.weekday() == 4 day_after_tomorrow = today + timedelta(days=4 if is_friday else 2) calendar = yf.Calendars(today, day_after_tomorrow) df = calendar.get_earnings_calendar(limit=100) unreported_df = df[df["Reported EPS"].isnull()] ``` ``` -------------------------------- ### Get Currency Instruments Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Lookup.html Retrieves a DataFrame containing currencies related to the query. ```APIDOC ## get_currency() ### Description Returns Currencies related financial instruments. ### Parameters - **count** (int) – The number of results to retrieve (default 25). ### Returns DataFrame containing currency instruments. ``` -------------------------------- ### Get Cryptocurrency Instruments Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Lookup.html Retrieves a DataFrame containing cryptocurrencies related to the query. ```APIDOC ## get_cryptocurrency() ### Description Returns Cryptocurrencies related financial instruments. ### Parameters - **count** (int) – The number of results to retrieve (default 25). ### Returns DataFrame containing cryptocurrency instruments. ``` -------------------------------- ### Get Institutional Holders Source: https://ranaroussi.github.io/yfinance/_sources/reference/api/yfinance.Ticker.institutional_holders.rst.txt This snippet demonstrates how to fetch institutional holders for a stock ticker. ```APIDOC ## Ticker.institutional_holders ### Description Returns a pandas DataFrame with institutional holders data. ### Method Attribute Access ### Parameters None ### Response #### Success Response - **DataFrame** (pandas.DataFrame) - DataFrame containing institutional holders information. ### Response Example ```python import yfinance as yf stock = yf.Ticker("AAPL") institutional_holders = stock.institutional_holders print(institutional_holders) ``` ``` -------------------------------- ### Get Mutual Fund Instruments Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Lookup.html Retrieves a DataFrame containing mutual funds related to the query. ```APIDOC ## get_mutualfund() ### Description Returns mutual funds related financial instruments. ### Parameters - **count** (int) – The number of results to retrieve (default 25). ### Returns DataFrame containing mutual fund instruments. ``` -------------------------------- ### Get All Financial Instruments Source: https://ranaroussi.github.io/yfinance/reference/api/yfinance.Lookup.html Retrieves a DataFrame containing all available financial instruments matching the query. ```APIDOC ## get_all() ### Description Returns all available financial instruments. ### Parameters - **count** (int) – The number of results to retrieve (default 25). ### Returns DataFrame containing financial instruments. ``` -------------------------------- ### Get Upgrades and Downgrades Source: https://ranaroussi.github.io/yfinance/_sources/reference/api/yfinance.Ticker.get_upgrades_downgrades.rst.txt Retrieves a pandas DataFrame containing analyst upgrades and downgrades for the stock. ```APIDOC ## Ticker.get_upgrades_downgrades ### Description Retrieves a pandas DataFrame containing analyst upgrades and downgrades for the stock. ### Method Signature `Ticker.get_upgrades_downgrades()` ### Parameters This method does not accept any parameters. ### Returns pandas.DataFrame: A DataFrame with columns like 'Date', 'Symbol', 'Firm', 'To Grade', 'From Grade', 'Action'. ``` -------------------------------- ### Clone Forked Repository Source: https://ranaroussi.github.io/yfinance/_sources/development/code.rst.txt Clone your forked repository to your local machine to begin development. ```bash git clone https://github.com/{user}/{repo}.git ``` -------------------------------- ### Get Major Holders Source: https://ranaroussi.github.io/yfinance/_sources/reference/api/yfinance.Ticker.get_major_holders.rst.txt Retrieves a pandas DataFrame containing information about the major holders of a stock. ```APIDOC ## Ticker.get_major_holders() ### Description Retrieves a pandas DataFrame containing information about the major holders of a stock. ### Method ```python ticker.get_major_holders() ``` ### Parameters This method does not accept any parameters. ### Response #### Success Response (DataFrame) Returns a pandas DataFrame with the following columns: - **Holder**: Name of the major holder. - **Shares**: Number of shares held. - **Date Reported**: The date the holdings were reported. - **% Out**: Percentage of outstanding shares held by the major holder. #### Response Example ```python # Example DataFrame structure (actual data will vary) # Shares Date Reported % Out # Holder # Vanguard Group Inc. 12345678 2023-09-30 0.10 # BlackRock Inc. 9876543 2023-09-30 0.08 # State Street Corporation 5432109 2023-09-30 0.05 ``` ``` -------------------------------- ### AsyncWebSocket Methods Source: https://ranaroussi.github.io/yfinance/_sources/reference/api/yfinance.AsyncWebSocket.rst.txt This section details the methods available for the AsyncWebSocket class, including initialization, closing connections, listening for messages, and subscribing/unsubscribing to data streams. ```APIDOC ## AsyncWebSocket ### Description Provides methods for managing asynchronous WebSocket connections. ### Methods #### `__init__` Initializes the AsyncWebSocket object. #### `close` Closes the WebSocket connection. #### `listen` Starts listening for messages on the WebSocket connection. #### `subscribe` Subscribes to a specific data stream or event. #### `unsubscribe` Unsubscribes from a specific data stream or event. ``` -------------------------------- ### Get Insider Roster Holders Source: https://ranaroussi.github.io/yfinance/_sources/reference/api/yfinance.Ticker.get_insider_roster_holders.rst.txt Retrieves a DataFrame containing insider roster holder information for the ticker. ```APIDOC ## Ticker.get_insider_roster_holders ### Description Retrieves a DataFrame containing insider roster holder information for the ticker. ### Method Signature `Ticker.get_insider_roster_holders()` ### Parameters This method does not accept any parameters. ### Returns - pandas.DataFrame: A DataFrame with insider roster holder data. The columns typically include 'Holder', 'Relation', 'Last Change', 'Shares', and 'Value'. ### Example ```python import yfinance as yf ticker = yf.Ticker("MSFT") insiders = ticker.get_insider_roster_holders() print(insiders) ``` ``` -------------------------------- ### get_recommendations Source: https://ranaroussi.github.io/yfinance/reference/yfinance.analysis.html Returns a DataFrame with the recommendations. Columns: period, strongBuy, buy, hold, sell, strongSell. ```APIDOC ## get_recommendations ### Description Returns a DataFrame containing stock recommendations. ### Parameters * `as_dict` (bool, optional): If True, returns a dictionary. Defaults to False. ### Returns DataFrame or dict: A DataFrame with recommendation data, or a dictionary if `as_dict` is True. ### Example ```python ticker.get_recommendations() ``` ``` -------------------------------- ### Get Balance Sheet Source: https://ranaroussi.github.io/yfinance/_sources/reference/api/yfinance.Ticker.get_balance_sheet.rst.txt Fetches the balance sheet data for the ticker. The data is returned as a pandas DataFrame. ```APIDOC ## Ticker.get_balance_sheet ### Description Retrieves the balance sheet data for the ticker. The data is returned as a pandas DataFrame. ### Method Signature `Ticker.get_balance_sheet(freq: str = 'quarterly') -> pandas.DataFrame` ### Parameters - **freq** (str, optional) - The frequency of the data to retrieve. Can be 'quarterly' or 'annual'. Defaults to 'quarterly'. ### Returns - **pandas.DataFrame** - A DataFrame containing the balance sheet data. ``` -------------------------------- ### Ticker Class Initialization and Usage 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 points like historical data, options, financials, and general information. ```APIDOC ## Ticker Class ### Description Initialize a Yahoo Finance Ticker object to access ticker data in a Pythonic way. ### Method Signature `Ticker(ticker[, session])` ### Usage Example ```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() ``` ```