### Get Financial Data Example Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/guide/ticker/financials.md Demonstrates how to fetch specific financial data points for a ticker. Ensure the `Ticker` class is imported and instantiated. ```python aapl = Ticker('aapl') types = ['TotalDebt', 'TotalAssets', 'EBIT', 'EBITDA', 'PeRatio'] aapl.get_financial_data(types, trailing=False) ``` -------------------------------- ### Get Screener Data Example Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/guide/screener.md This snippet demonstrates retrieving detailed financial data for multiple stocks using the screener functionality. It includes metrics like market cap, P/E ratio, and daily trading information. ```python { 'twoHundredDayAverageChange': -2.1995683, 'twoHundredDayAverageChangePercent': -0.26598343, 'marketCap': 53094838272, 'forwardPE': 15.973685, 'priceToBook': 1.5782632, 'sourceInterval': 15, 'exchangeDataDelayedBy': 0, 'exchangeTimezoneName': 'America/New_York', 'exchangeTimezoneShortName': 'EDT', 'gmtOffSetMilliseconds': -14400000, 'esgPopulated': False, 'tradeable': True, 'regularMarketChangePercent': -3.0351446, 'displayName': 'General Electric', 'symbol': 'GE' }, { 'language': 'en-US', 'region': 'US', 'quoteType': 'EQUITY', 'quoteSourceName': 'Nasdaq Real Time Price', 'triggerable': False, 'currency': 'USD', 'firstTradeDateMilliseconds': 757607400000, 'priceHint': 4, 'postMarketChangePercent': -0.7314493, 'postMarketTime': 1596234026, 'postMarketPrice': 4.75, 'postMarketChange': -0.034999847, 'regularMarketChange': 0.3300004, 'regularMarketTime': 1596225601, 'regularMarketPrice': 4.78, 'regularMarketDayHigh': 4.95, 'regularMarketDayRange': '4.635 - 4.95', 'regularMarketDayLow': 4.635, 'regularMarketVolume': 117123629, 'regularMarketPreviousClose': 4.45, 'bid': 4.73, 'ask': 4.76, 'bidSize': 369, 'askSize': 400, 'exchange': 'NYQ', 'market': 'us_market', 'messageBoardId': 'finmb_205573', 'fullExchangeName': 'NYSE', 'shortName': 'Nokia Corporation Sponsored', 'longName': 'Nokia Corporation', 'financialCurrency': 'EUR', 'regularMarketOpen': 4.86, 'averageDailyVolume3Month': 30349318, 'averageDailyVolume10Day': 27909325, 'fiftyTwoWeekLowChange': 2.4400003, 'fiftyTwoWeekLowChangePercent': 1.0427352, 'fiftyTwoWeekRange': '2.34 - 5.45', 'fiftyTwoWeekHighChange': -0.6699996, 'fiftyTwoWeekHighChangePercent': -0.12293571, 'fiftyTwoWeekLow': 2.34, 'fiftyTwoWeekHigh': 5.45, 'dividendDate': 1565654400, 'trailingAnnualDividendRate': 0.221, 'trailingAnnualDividendYield': 0.049662925, 'marketState': 'POST', 'epsTrailingTwelveMonths': -0.192, 'epsForward': 0.31, 'sharesOutstanding': 5618930176, 'bookValue': 3.119, 'fiftyDayAverage': 4.3285713, 'fiftyDayAverageChange': 0.4514289, 'fiftyDayAverageChangePercent': 0.10429051, 'twoHundredDayAverage': 3.8270504, 'twoHundredDayAverageChange': 0.95294976, 'twoHundredDayAverageChangePercent': 0.24900371, 'marketCap': 25653735424, 'forwardPE': 15.419355, 'priceToBook': 1.5325426, 'sourceInterval': 15, 'exchangeDataDelayedBy': 0, 'exchangeTimezoneName': 'America/New_York', 'exchangeTimezoneShortName': 'EDT', 'gmtOffSetMilliseconds': -14400000, 'esgPopulated': False, 'tradeable': True, 'regularMarketChangePercent': 7.4157395, 'displayName': 'Nokia', 'symbol': 'NOK' }, { 'language': 'en-US', 'region': 'US', 'quoteType': 'EQUITY', 'quoteSourceName': 'Delayed Quote', 'triggerable': False, 'currency': 'USD', 'firstTradeDateMilliseconds': 76253400000, 'priceHint': 2, 'postMarketChangePercent': -0.30257156, 'postMarketTime': 1596234024, 'postMarketPrice': 6.59, 'postMarketChange': -0.01999998, 'regularMarketChange': -0.12999964, 'regularMarketTime': 1596225883, 'regularMarketPrice': 6.61, 'regularMarketDayHigh': 6.9, 'regularMarketDayRange': '6.52 - 6.9', 'regularMarketDayLow': 6.52, 'regularMarketVolume': 115075556, 'regularMarketPreviousClose': 6.74, 'bid': 6.6, 'ask': 6.6, 'bidSize': 292, 'askSize': 18, 'exchange': 'NYQ' } ``` -------------------------------- ### Install yahooquery Source: https://github.com/dpguthrie/yahooquery/blob/master/README.md Install the package with or without premium support. For premium features, use `pip install yahooquery[premium]`. ```bash pip install yahooquery[premium] ``` ```bash pip install yahooquery ``` ```bash uv pip install yahooquery ``` -------------------------------- ### Example Search Result Data Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/guide/misc.md This is an example of the data structure returned by a successful search query, containing details about a financial instrument. ```python { 'exchange': 'NYQ', 'quoteType': 'EQUITY', 'symbol': 'GS', 'index': 'quotes', 'score': 33156.0, 'typeDisp': 'Equity', 'longname': 'The Goldman Sachs Group, Inc.', 'isYahooFinance': True } ``` -------------------------------- ### Get Ticker Recommendations Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/guide/ticker/miscellaneous.md Retrieve recommendations for a given set of ticker symbols. Ensure the Ticker object is initialized with the desired symbols. ```python tickers = Ticker('aapl gs hasgx ^GSPC ezu') tickers.recommendations ``` -------------------------------- ### Fetch All Trade Ideas Source: https://context7.com/dpguthrie/yahooquery/llms.txt Retrieves all available trade ideas. This can be used to get a broad overview of potential trading opportunities. ```python trades = r.trades() print(trades.columns.tolist()) ``` -------------------------------- ### Trade Options: Start Datetime Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/guide/research.md Defines the available options and whether multiple selections are allowed for the 'startdatetime' argument in the `trades` method. ```json { 'options': { 'Last Week': 7, 'Last Month': 30, 'Last Year': 365 }, 'multiple': False } ``` -------------------------------- ### Get Supported Currencies Source: https://context7.com/dpguthrie/yahooquery/llms.txt Retrieves a list of all supported currency pairs. This can be used to understand available currency exchange data. ```python from yahooquery import get_currencies, get_exchanges # All supported currencies currencies = get_currencies() print(currencies[:3]) ``` -------------------------------- ### Get Market Summary for Hong Kong Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/guide/misc.md Fetches the market summary for a specified country. Ensure the country is supported and listed in the available options. ```python import yahooquery as yq yq.get_market_summary(country='hong kong') ``` -------------------------------- ### Screener Quote Data Example Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/guide/screener.md This snippet displays a sample of quote data returned from a screener query. It includes various financial metrics for a specific stock. ```json { 'language': 'en-US', 'region': 'US', 'quoteType': 'EQUITY', 'quoteSourceName': 'Delayed Quote', 'triggerable': False, 'currency': 'USD', 'firstTradeDateMilliseconds': 1555594200000, 'priceHint': 2, 'postMarketChangePercent': 1.6622913, 'postMarketTime': 1596234159, 'postMarketPrice': 34.86, 'postMarketChange': 0.5699997, 'regularMarketChange': 9.1, 'regularMarketTime': 1596225602, 'regularMarketPrice': 34.29, 'regularMarketDayHigh': 34.5, 'regularMarketDayRange': '31.0 - 34.5', 'regularMarketDayLow': 31.0, 'regularMarketVolume': 111167386, 'regularMarketPreviousClose': 25.19, 'bid': 34.69, 'ask': 34.7, 'bidSize': 13, 'askSize': 18, 'exchange': 'NYQ', 'market': 'us_market', 'messageBoardId': 'finmb_139264388', 'fullExchangeName': 'NYSE', 'shortName': 'Pinterest, Inc.', 'longName': 'Pinterest, Inc.', 'financialCurrency': 'USD', 'regularMarketOpen': 33.56, 'averageDailyVolume3Month': 13862671, 'averageDailyVolume10Day': 9896450, 'fiftyTwoWeekLowChange': 24.19, 'fiftyTwoWeekLowChangePercent': 2.3950496, 'fiftyTwoWeekRange': '10.1 - 36.83', 'fiftyTwoWeekHighChange': -2.540001, 'fiftyTwoWeekHighChangePercent': -0.06896554, 'fiftyTwoWeekLow': 10.1, 'fiftyTwoWeekHigh': 36.83, 'earningsTimestamp': 1596184200, 'earningsTimestampStart': 1603987200, 'earningsTimestampEnd': 1604332800, 'marketState': 'POST', 'epsTrailingTwelveMonths': -2.743, 'epsForward': 0.05, 'sharesOutstanding': 403489984, 'bookValue': 3.332, 'fiftyDayAverage': 24.036858, 'fiftyDayAverageChange': 10.253143, 'fiftyDayAverageChangePercent': 0.4265592, 'twoHundredDayAverage': 20.366547, 'twoHundredDayAverageChange': 13.923454, 'twoHundredDayAverageChangePercent': 0.68364334, 'marketCap': 20109576192, 'forwardPE': 685.8, 'priceToBook': 10.291117, 'sourceInterval': 15, 'exchangeDataDelayedBy': 0, 'exchangeTimezoneName': 'America/New_York', 'exchangeTimezoneShortName': 'EDT', 'gmtOffSetMilliseconds': -14400000, 'esgPopulated': False, 'tradeable': True, 'regularMarketChangePercent': 36.12545, 'displayName': 'Pinterest', 'symbol': 'PINS' } ``` ```json { 'language': 'en-US', 'region': 'US', 'quoteType': 'EQUITY', 'quoteSourceName': 'Delayed Quote', 'triggerable': False, 'currency': 'USD', 'firstTradeDateMilliseconds': 1234535400000, 'priceHint': 4, 'regularMarketChange': 0.1509, 'regularMarketTime': 1596222445, 'regularMarketPrice': 0.7009, 'regularMarketDayHigh': 1.5, 'regularMarketDayRange': '0.7009 - 1.5', 'regularMarketDayLow': 0.7009, 'regularMarketVolume': 885738, 'regularMarketPreviousClose': 0.55, 'bid': 0.0, 'ask': 0.0, 'bidSize': 0, 'askSize': 0, 'exchange': 'PNK', 'market': 'us_market', 'messageBoardId': 'finmb_92126', 'fullExchangeName': 'Other OTC' } ``` -------------------------------- ### Get Screeners with YahooQuery Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/guide/screener.md Instantiate the Screener class and call get_screeners with a list of screen IDs and a count to retrieve securities. The result is a pandas DataFrame. ```python s = Screener() s.get_screeners(['most_actives', 'day_gainers'], 5) ``` -------------------------------- ### Market Summary Data Structure Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/guide/misc.md This is an example of the data structure returned by `get_market_summary`, showing details for S&P 500 and Dow 30 indices. ```python [ { 'exchangeTimezoneName': 'America/New_York', 'fullExchangeName': 'SNP', 'symbol': '^GSPC', 'regularMarketChange': { 'raw': 24.900146, 'fmt': '24.90' }, 'gmtOffSetMilliseconds': -14400000, 'exchangeDataDelayedBy': 0, 'firstTradeDateMilliseconds': -1325583000000, 'language': 'en-US', 'regularMarketTime': { 'raw': 1596229659, 'fmt': '5:07PM EDT' }, 'exchangeTimezoneShortName': 'EDT', 'regularMarketChangePercent': { 'raw': 0.7670505, 'fmt': '0.77%' }, 'quoteType': 'INDEX', 'marketState': 'POSTPOST', 'regularMarketPrice': { 'raw': 3271.12, 'fmt': '3,271.12' }, 'market': 'us_market', 'quoteSourceName': 'Delayed Quote', 'priceHint': 2, 'tradeable': False, 'exchange': 'SNP', 'sourceInterval': 15, 'region': 'US', 'shortName': 'S&P 500', 'triggerable': False, 'regularMarketPreviousClose': { 'raw': 3246.22, 'fmt': '3,246.22' } }, { 'exchangeTimezoneName': 'America/New_York', 'fullExchangeName': 'DJI', 'symbol': '^DJI', 'regularMarketChange': { 'raw': 114.66992, 'fmt': '114.67' }, 'gmtOffSetMilliseconds': -14400000, 'exchangeDataDelayedBy': 0, 'firstTradeDateMilliseconds': 475857000000, 'language': 'en-US', 'regularMarketTime': { 'raw': 1596229659, 'fmt': '5:07PM EDT' }, 'exchangeTimezoneShortName': 'EDT', 'regularMarketChangePercent': { 'raw': 0.43578112, 'fmt': '0.44%' }, 'quoteType': 'INDEX', 'marketState': 'POSTPOST', 'regularMarketPrice': { 'raw': 26428.32, 'fmt': '26,428.32' }, 'market': 'us_market', 'quoteSourceName': 'Delayed Quote', 'priceHint': 2, 'tradeable': False, 'exchange': 'DJI', 'sourceInterval': 120, 'region': 'US', 'shortName': 'Dow 30', ``` -------------------------------- ### Get Option Chain Data Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/alternative.ipynb This code retrieves the option chain for a given stock symbol. It's a common starting point for analyzing options data. ```python %%time yq_option_chain = YQ_aapl.option_chain ``` ```python yq_option_chain ``` -------------------------------- ### Ticker Class Instantiation Source: https://context7.com/dpguthrie/yahooquery/llms.txt Demonstrates how to instantiate the Ticker class with single or multiple symbols, and with various configuration options. ```APIDOC ## Ticker Class ### Instantiating Ticker with one or multiple symbols The `Ticker` class is the primary entry point; pass a symbol string (space- or comma-separated for multiple tickers) or a list, along with optional keyword arguments that configure session behavior. ```python from yahooquery import Ticker # Single symbol aapl = Ticker('aapl') # Multiple symbols (space-separated string) tech = Ticker('aapl msft goog amzn') # Multiple symbols (list) faang = Ticker(['fb', 'aapl', 'amzn', 'nflx', 'goog']) # With keyword arguments t = Ticker( 'aapl msft', asynchronous=True, # concurrent requests max_workers=4, timeout=10, retry=5, validate=True, # drop invalid symbols on init country='United States', progress=True, # tqdm progress bar ) print(t.symbols) # ['AAPL', 'MSFT'] print(t.invalid_symbols) # [] (only populated when validate=True) ``` ``` -------------------------------- ### Initialize Research with Credentials Source: https://context7.com/dpguthrie/yahooquery/llms.txt Initializes the Research object with username and password for accessing premium features. Ensure your credentials are kept secure. ```python from yahooquery import Research r = Research(username='your@email.com', password='yourpassword') ``` -------------------------------- ### Get Fund Bond Ratings Source: https://context7.com/dpguthrie/yahooquery/llms.txt Retrieves bond ratings for fixed-income funds. Requires the 'fund_bond_ratings' attribute. ```python from yahooquery import Ticker # Bond ratings (for fixed-income funds) agi = Ticker('agi') ratings = agi.fund_bond_ratings print(ratings) ``` -------------------------------- ### Get Insider Holdings Source: https://context7.com/dpguthrie/yahooquery/llms.txt Fetches and displays insider holdings for a given ticker. Requires the 'insider_holders' attribute. ```python from yahooquery import Ticker t = Ticker('aapl') holders = t.insider_holders print(holders[['name', 'relation', 'positionDirect', 'latestTransDate']].head()) ``` -------------------------------- ### Create Screener Instance Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/guide/screener.md Instantiate the Screener class to create an object that can be used to fetch screener data. ```python s = Screener() ``` -------------------------------- ### Get Summary Pricing and Market Data Source: https://context7.com/dpguthrie/yahooquery/llms.txt Retrieve summary pricing metrics like previous close, open, beta, market cap, and dividend yield for each symbol. This data is returned as a dictionary where keys are symbols and values are dictionaries of metrics. ```python from yahooquery import Ticker t = Ticker('aapl msft') data = t.summary_detail # Expected output structure: # { # 'aapl': {'previousClose': 189.3, 'open': 190.1, 'beta': 1.29, # 'marketCap': 2960000000000, 'dividendYield': 0.0053, ...}, # 'msft': {'previousClose': 415.5, 'open': 417.2, 'beta': 0.89, ...} # } print(data['aapl']['marketCap']) # e.g. 2960000000000 print(data['msft']['dividendYield']) ``` -------------------------------- ### Get French Market Summary Source: https://context7.com/dpguthrie/yahooquery/llms.txt Retrieves the market summary specifically for France. This allows for regional market analysis. ```python # French market summary fr_summary = get_market_summary(country='France') ``` -------------------------------- ### Get Fund Sector Weightings Source: https://context7.com/dpguthrie/yahooquery/llms.txt Retrieves the sector weightings for an ETF or mutual fund. Requires the 'fund_sector_weightings' attribute. ```python from yahooquery import Ticker # S&P 500 ETF spy = Ticker('spy') # Sector weightings sectors = spy.fund_sector_weightings print(sectors) # DataFrame: sector -> weight ``` -------------------------------- ### Create Ticker Instance for Multiple Stocks (List) Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/guide/ticker/intro.md Pass a list of stock symbols to the Ticker constructor to create an instance that can fetch data for multiple companies simultaneously. ```python symbols = ['fb', 'aapl', 'amzn', 'nflx', 'goog'] tickers = Ticker(symbols) ``` -------------------------------- ### Get Fund Ownership Source: https://context7.com/dpguthrie/yahooquery/llms.txt Retrieves the top fund owners for a given stock symbol. Requires the 'fund_ownership' attribute. ```python from yahooquery import Ticker t = Ticker('aapl') # Top fund owners funds = t.fund_ownership print(funds[['organization', 'pctHeld', 'shares', 'reportDate']].head(5)) ``` -------------------------------- ### Import YahooQuery Library Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/guide/misc.md Import the yahooquery library for use in your project. This is a common first step for utilizing the library's functionalities. ```python import yahooquery as yq ``` -------------------------------- ### Create Ticker Instance for Multiple Stocks (String) Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/guide/ticker/intro.md Alternatively, provide a space-separated string of stock symbols to the Ticker constructor for multi-company data retrieval. ```python symbols = 'fb aapl amzn nflx goog' tickers = Ticker(symbols) ``` -------------------------------- ### Get Institutional Ownership Source: https://context7.com/dpguthrie/yahooquery/llms.txt Retrieves the top institutional owners for a given stock symbol. Requires the 'institution_ownership' attribute. ```python from yahooquery import Ticker t = Ticker('aapl') # Top institutional owners inst = t.institution_ownership print(inst[['organization', 'pctHeld', 'shares', 'value']].head(5)) ``` -------------------------------- ### Screener Data Structure Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/guide/screener.md This is an example of the data structure returned by the get_screeners method, detailing screener information and quotes for securities. ```json { 'most_actives': { 'id': '437465ef-980e-4d8c-a860-de7cbfbab373', 'title': 'Most Actives - US', 'description': 'Stocks ordered in descending order by intraday trade volume', 'canonicalName': 'MOST_ACTIVES', 'criteriaMeta': { 'size': 5, 'offset': 0, 'sortField': 'dayvolume', 'sortType': 'DESC', 'quoteType': 'EQUITY', 'topOperator': 'AND', 'criteria': [{ 'field': 'region', 'operators': ['EQ'], 'values': [], 'labelsSelected': [53] }, { 'field': 'intradaymarketcap', 'operators': ['EQ'], 'values': [], 'labelsSelected': [1, 2, 3] }, { 'field': 'dayvolume', 'operators': ['GT'], 'values': [5000000], 'labelsSelected': [] }] }, 'rawCriteria': '{"offset":0,"size":5,"sortField":"dayvolume","sortType":"DESC","quoteType":"EQUITY","query":{"operator":"AND","operands":[{\"operator\":\"eq\",\"operands\":[\"region\",\"us\"]},{\"operator\":\"or\",\"operands\":[{\"operator\":\"BTWN\",\"operands\":[\"intradaymarketcap\",2000000000,10000000000]},{\"operator\":\"BTWN\",\"operands\":[\"intradaymarketcap\",10000000000,100000000000]},{\"operator\":\"GT\",\"operands\":[\"intradaymarketcap\",100000000000]}]},{\"operator\":\"gt\",\"operands\":[\"dayvolume\",5000000]}]}}', 'start': 0, 'count': 5, 'total': 203, 'quotes': [{ 'language': 'en-US', 'region': 'US', 'quoteType': 'EQUITY', 'quoteSourceName': 'Nasdaq Real Time Price', 'triggerable': False, 'currency': 'USD', 'firstTradeDateMilliseconds': -252322200000, 'priceHint': 2, 'postMarketChangePercent': 0.0, 'postMarketTime': 1596234164, 'postMarketPrice': 6.08, 'postMarketChange': 0.0, 'regularMarketChange': -0.19000006, 'regularMarketTime': 1596225602, 'regularMarketPrice': 6.07, 'regularMarketDayHigh': 6.29, 'regularMarketDayRange': '6.0 - 6.29', 'regularMarketDayLow': 6.0, 'regularMarketVolume': 142268197, 'regularMarketPreviousClose': 6.26, 'bid': 6.07, 'ask': 6.08, 'bidSize': 473, 'askSize': 280, 'exchange': 'NYQ', 'market': 'us_market', 'messageBoardId': 'finmb_177031', 'fullExchangeName': 'NYSE', 'shortName': 'General Electric Company', 'longName': 'General Electric Company', 'financialCurrency': 'USD', 'regularMarketOpen': 6.25, 'averageDailyVolume3Month': 103055092, 'averageDailyVolume10Day': 86456425, 'fiftyTwoWeekLowChange': 0.59000015, 'fiftyTwoWeekLowChangePercent': 0.107664265, 'fiftyTwoWeekRange': '5.48 - 13.26', 'fiftyTwoWeekHighChange': -7.19, 'fiftyTwoWeekHighChangePercent': -0.5422323, 'fiftyTwoWeekLow': 5.48, 'fiftyTwoWeekHigh': 13.26, 'dividendDate': 1595808000, 'earningsTimestamp': 1603873800, 'earningsTimestampStart': 1603873800, 'earningsTimestampEnd': 1603873800, 'trailingAnnualDividendRate': 0.04, 'trailingAnnualDividendYield': 0.006389776, 'marketState': 'POST', 'epsTrailingTwelveMonths': -0.561, 'epsForward': 0.38, 'sharesOutstanding': 8747089920, 'bookValue': 3.846, 'fiftyDayAverage': 6.9014287, 'fiftyDayAverageChange': -0.8314285, 'fiftyDayAverageChangePercent': -0.12047195, 'twoHundredDayAverage': 8.269568 }] } } ``` -------------------------------- ### Get Balance Sheet Data Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/guide/ticker/financials.md Retrieve specific balance sheet items for a ticker. Ensure 'types' argument is provided. ```python [ 'AccountsPayable', 'AccountsReceivable', 'AccruedInterestReceivable', 'AccumulatedDepreciation', 'AdditionalPaidInCapital', 'AllowanceForDoubtfulAccountsReceivable', 'AssetsHeldForSaleCurrent', 'AvailableForSaleSecurities', 'BuildingsAndImprovements', 'CapitalLeaseObligations', 'CapitalStock', 'CashAndCashEquivalents', 'CashCashEquivalentsAndShortTermInvestments', 'CashEquivalents', 'CashFinancial', 'CommercialPaper', 'CommonStock', 'CommonStockEquity', 'ConstructionInProgress', 'CurrentAccruedExpenses', 'CurrentAssets', 'CurrentCapitalLeaseObligation', 'CurrentDebt', 'CurrentDebtAndCapitalLeaseObligation', 'CurrentDeferredAssets', 'CurrentDeferredLiabilities', 'CurrentDeferredRevenue', 'CurrentDeferredTaxesAssets', 'CurrentDeferredTaxesLiabilities', 'CurrentLiabilities', 'CurrentNotesPayable', 'CurrentProvisions', 'DefinedPensionBenefit', 'DerivativeProductLiabilities', 'DividendsPayable', 'DuefromRelatedPartiesCurrent', 'DuefromRelatedPartiesNonCurrent', 'DuetoRelatedPartiesCurrent', 'DuetoRelatedPartiesNonCurrent', 'EmployeeBenefits', 'FinancialAssets', 'FinancialAssetsDesignatedasFairValueThroughProfitorLossTotal', 'FinishedGoods', 'FixedAssetsRevaluationReserve', 'ForeignCurrencyTranslationAdjustments', 'GainsLossesNotAffectingRetainedEarnings', 'GeneralPartnershipCapital', 'Goodwill', 'GoodwillAndOtherIntangibleAssets', 'GrossAccountsReceivable', 'GrossPPE', 'HedgingAssetsCurrent', 'HeldToMaturitySecurities', 'IncomeTaxPayable', 'InterestPayable', 'InventoriesAdjustmentsAllowances', 'Inventory', 'InvestedCapital', 'InvestmentProperties', 'InvestmentinFinancialAssets', 'InvestmentsAndAdvances', 'InvestmentsInOtherVenturesUnderEquityMethod', 'InvestmentsinAssociatesatCost', 'InvestmentsinJointVenturesatCost', 'InvestmentsinSubsidiariesatCost', 'LandAndImprovements', 'Leases', 'LiabilitiesHeldforSaleNonCurrent', 'LimitedPartnershipCapital', 'LineOfCredit', 'LoansReceivable', 'LongTermCapitalLeaseObligation', 'LongTermDebt', 'LongTermDebtAndCapitalLeaseObligation', 'LongTermEquityInvestment', 'LongTermProvisions', 'MachineryFurnitureEquipment', 'MinimumPensionLiabilities', 'MinorityInterest', 'NetDebt', 'NetPPE', 'NetTangibleAssets', 'NonCurrentAccountsReceivable', 'NonCurrentAccruedExpenses', 'NonCurrentDeferredAssets', 'NonCurrentDeferredLiabilities', 'NonCurrentDeferredRevenue', 'NonCurrentDeferredTaxesAssets', 'NonCurrentDeferredTaxesLiabilities', 'NonCurrentNoteReceivables', 'NonCurrentPensionAndOtherPostretirementBenefitPlans', 'NonCurrentPrepaidAssets', 'NotesReceivable', 'OrdinarySharesNumber', 'OtherCapitalStock', 'OtherCurrentAssets', 'OtherCurrentBorrowings', 'OtherCurrentLiabilities', 'OtherEquityAdjustments', 'OtherEquityInterest', 'OtherIntangibleAssets', 'OtherInventories', 'OtherInvestments', 'OtherNonCurrentAssets', 'OtherNonCurrentLiabilities', 'OtherPayable', 'OtherProperties', 'OtherReceivables', 'OtherShortTermInvestments', 'Payables', 'PayablesAndAccruedExpenses', 'PensionandOtherPostRetirementBenefitPlansCurrent', 'PreferredSecuritiesOutsideStockEquity', 'PreferredSharesNumber', 'PreferredStock', 'PreferredStockEquity', 'PrepaidAssets', 'Properties', 'RawMaterials', 'Receivables', 'ReceivablesAdjustmentsAllowances', 'RestrictedCash', 'RestrictedCommonStock', 'RetainedEarnings', 'ShareIssued', 'StockholdersEquity', 'TangibleBookValue', 'TaxesReceivable', 'TotalAssets', 'TotalCapitalization', 'TotalDebt' ] ``` -------------------------------- ### Fetch All Modules for Multiple Tickers (Asynchronous) Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/alternative.ipynb This asynchronous approach is generally faster for fetching all modules for multiple tickers. It requires the `asynchronous=True` flag during Ticker initialization. ```python tickers = Ticker(symbols, asynchronous=True) data = tickers.all_modules ``` ```python data['FB'].keys() ``` -------------------------------- ### Get Available Screeners - Python Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/guide/screener.md Instantiate the Screener class and access the `available_screeners` attribute to retrieve a dictionary of predefined screeners. This is useful for understanding the available filtering options for stock data. ```python s = Screener() s.available_screeners ``` -------------------------------- ### Get Fund Top Holdings Source: https://context7.com/dpguthrie/yahooquery/llms.txt Retrieves the top 10 holdings for an ETF or mutual fund. Requires the 'fund_top_holdings' attribute. ```python from yahooquery import Ticker # S&P 500 ETF spy = Ticker('spy') # Top 10 holdings as DataFrame holdings = spy.fund_top_holdings print(holdings[['symbol', 'holdingName', 'holdingPercent']].head(10)) ``` -------------------------------- ### Get Market Summary Data Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/guide/misc.md This snippet demonstrates how to retrieve market summary data for different exchanges. It shows the structure of the returned data, including price, change, and time information. ```python { 'regularMarketTime': { 'raw': 1596210339, 'fmt': '4:45PM BST' }, 'exchangeTimezoneShortName': 'BST', 'regularMarketChangePercent': { 'raw': -1.5397432, 'fmt': '-1.54%' }, 'quoteType': 'INDEX', 'marketState': 'CLOSED', 'regularMarketPrice': { 'raw': 5897.76, 'fmt': '5,897.76' }, 'market': 'gb_market', 'priceHint': 2, 'tradeable': False, 'exchange': 'FGI', 'sourceInterval': 15, 'region': 'US', 'shortName': 'FTSE 100', 'triggerable': False, 'regularMarketPreviousClose': { 'raw': 5989.99, 'fmt': '5,989.99' } }, { 'exchangeTimezoneName': 'Asia/Tokyo', 'fullExchangeName': 'Osaka', 'symbol': '^N225', 'regularMarketChange': { 'raw': -629.23047, 'fmt': '-629.23' }, 'gmtOffSetMilliseconds': 32400000, 'exchangeDataDelayedBy': 0, 'firstTradeDateMilliseconds': -157420800000, 'language': 'en-US', 'regularMarketTime': { 'raw': 1596176103, 'fmt': '3:15PM JST' }, 'exchangeTimezoneShortName': 'JST', 'regularMarketChangePercent': { 'raw': -2.8167062, 'fmt': '-2.82%' }, 'quoteType': 'INDEX', 'marketState': 'CLOSED', 'regularMarketPrice': { 'raw': 21710.0, 'fmt': '21,710.00' }, 'market': 'jp_market', 'priceHint': 2, 'tradeable': False, 'exchange': 'OSA', 'sourceInterval': 20, 'region': 'US', 'shortName': 'Nikkei 225', 'triggerable': False, 'regularMarketPreviousClose': { 'raw': 22339.23, 'fmt': '22,339.23' } }] ``` -------------------------------- ### Get Key Statistics (PE, EPS, EBITDA) Source: https://context7.com/dpguthrie/yahooquery/llms.txt Access key statistics including enterprise value, P/E ratio, PEG ratio, EPS, short interest, and book value. The results are provided in a dictionary, with each symbol mapping to its statistics. ```python from yahooquery import Ticker t = Ticker('aapl msft goog') stats = t.key_stats # { # 'aapl': {'enterpriseValue': 3100000000000, 'trailingEps': 6.43, # 'pegRatio': 2.85, 'shortPercentOfFloat': 0.0073, ...}, # 'msft': {...}, # 'goog': {...} # } for symbol, s in stats.items(): print(f"{symbol}: EPS={s.get('trailingEps')}, PE={s.get('forwardPE')}") ``` -------------------------------- ### Get Institutional Ownership for a Symbol Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/guide/ticker/modules.md Retrieve the top institutional owners for a specified stock symbol. The result is provided as a pandas DataFrame. ```python aapl = Ticker('aapl') aapl.institution_ownership ``` -------------------------------- ### Get Insider Transactions for a Symbol Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/guide/ticker/modules.md Retrieve insider transaction data for a specified stock symbol. This data is returned as a pandas DataFrame. ```python aapl = Ticker('aapl') df = aapl.insider_transactions df.head() ``` -------------------------------- ### Get UK Trending Stocks Source: https://context7.com/dpguthrie/yahooquery/llms.txt Retrieves the trending stock symbols for the United Kingdom market. This enables regional trend identification. ```python # UK trending uk_trending = get_trending(country='United Kingdom') print(uk_trending['quotes'][:5]) ``` -------------------------------- ### all_modules Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/guide/ticker/modules.md Returns all available modules for a ticker symbol. Each module is a key in the returned dictionary. ```APIDOC ## all_modules ### Description Returns all modules from the ticker. Each module will be a key in the dictionary returned. ### Method Attribute Access ### Endpoint N/A (Attribute of Ticker object) ### Parameters None ### Request Example ```python aapl = Ticker('aapl') data = aapl.all_modules ``` ### Response #### Success Response (dict) - **Keys**: Module names (e.g., 'assetProfile', 'quoteType') #### Response Example ```json { "aapl": { "assetProfile": { ... }, "recommendationTrend": { ... }, "cashflowStatementHistory": { ... }, "indexTrend": { ... }, "defaultKeyStatistics": { ... }, "industryTrend": { ... }, "quoteType": { ... }, "incomeStatementHistory": { ... }, "fundOwnership": { ... }, "summaryDetail": { ... }, "insiderHolders": { ... }, "calendarEvents": { ... }, "upgradeDowngradeHistory": { ... }, "price": { ... }, "balanceSheetHistory": { ... }, "earningsTrend": { ... }, "secFilings": { ... }, "institutionOwnership": { ... }, "majorHoldersBreakdown": { ... }, "balanceSheetHistoryQuarterly": { ... }, "earningsHistory": { ... }, "esgScores": { ... }, "summaryProfile": { ... }, "netSharePurchaseActivity": { ... }, "insiderTransactions": { ... }, "sectorTrend": { ... }, "incomeStatementHistoryQuarterly": { ... }, "cashflowStatementHistoryQuarterly": { ... }, "earnings": { ... }, "pageViews": { ... }, "financialData": { ... } } } ``` ### Warnings Data for symbols external to the United States will be inaccurate for the following modules: `cashFlowStatementHistory`, `cashFlowStatementHistoryQuarterly`, `incomeStatementHistory`, `incomeStatementHistoryQuarterly`, `balanceSheetHistory`, `balanceSheetHistoryQuarterly`. ``` -------------------------------- ### Get Fund Category Holdings Source: https://context7.com/dpguthrie/yahooquery/llms.txt Retrieves the category breakdown (cash, bonds, equity percentages) for a fund. Requires the 'fund_category_holdings' attribute. ```python from yahooquery import Ticker # S&P 500 ETF spy = Ticker('spy') # Category breakdown (cash, bonds, equity percentages) categories = spy.fund_category_holdings print(categories) ``` -------------------------------- ### Get Fund Performance Source: https://context7.com/dpguthrie/yahooquery/llms.txt Retrieves fund performance data, including trailing returns, compared to its category. Requires the 'fund_performance' attribute. ```python from yahooquery import Ticker # S&P 500 ETF spy = Ticker('spy') # Fund performance vs category perf = spy.fund_performance print(perf['spy']['trailingReturns']) ``` -------------------------------- ### Get Historical Dividend Payments Source: https://context7.com/dpguthrie/yahooquery/llms.txt Retrieves historical dividend payments for specified symbols over a date range. Returns a pandas Series. ```python from yahooquery import Ticker t = Ticker('aapl msft') # Last 5 years of dividends divs = t.dividend_history(start='2019-01-01', end='2024-01-01') print(divs) ``` -------------------------------- ### Instantiate Ticker with Symbols Source: https://context7.com/dpguthrie/yahooquery/llms.txt Initialize the Ticker class with one or more stock symbols. Symbols can be provided as a space-separated string, a comma-separated string, or a list. Optional keyword arguments can configure session behavior, including asynchronous requests, timeouts, retries, and validation. ```python from yahooquery import Ticker # Single symbol aapl = Ticker('aapl') # Multiple symbols (space-separated string) tech = Ticker('aapl msft goog amzn') # Multiple symbols (list) faang = Ticker(['fb', 'aapl', 'amzn', 'nflx', 'goog']) # With keyword arguments t = Ticker( 'aapl msft', asynchronous=True, # concurrent requests max_workers=4, timeout=10, retry=5, validate=True, # drop invalid symbols on init country='United States', progress=True, # tqdm progress bar ) print(t.symbols) # ['AAPL', 'MSFT'] print(t.invalid_symbols) # [] (only populated when validate=True) ``` -------------------------------- ### Get Company Officers Data Source: https://context7.com/dpguthrie/yahooquery/llms.txt Retrieves executive compensation data as a pandas DataFrame. Requires a Ticker object initialized with a symbol. ```python from yahooquery import Ticker t = Ticker('aapl') officers = t.company_officers # pandas DataFrame with columns: name, title, totalPay, exercisedValue, ... # MultiIndex: (symbol, row) print(officers.head()) ``` -------------------------------- ### Instantiate Research Class Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/guide/research.md Create an instance of the Research class by providing your Yahoo Finance username and password. Authentication is required to access premium features. ```python r = Research(username='username@yahoo.com', password='password') ``` -------------------------------- ### Get Supported Currencies Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/guide/misc.md Retrieves a list of currencies that are supported by Yahoo Finance. This can be useful for understanding the scope of available currency data. ```APIDOC ## get_currencies ### Description List of currencies Yahoo Finance supports. ### Method ```python yq.get_currencies() ``` ### Returns `list` - A list of dictionaries, where each dictionary represents a currency with its details. ### Example ```python import yahooquery as yq data = yq.get_currencies() ``` ### Data Structure Example ```json [ { "shortName": "FJD", "longName": "Fijian Dollar", "symbol": "FJD", "localLongName": "Fijian Dollar" }, { "shortName": "MXN", "longName": "Mexican Peso", "symbol": "MXN", "localLongName": "Mexican Peso" } ] ``` ``` -------------------------------- ### Inspect Downloaded Data Structure Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/alternative.ipynb Checks the data type, shape, and displays the first few rows of the downloaded financial data. This helps in understanding the structure and content of the fetched data. ```python type(yf_data) yf_data.shape yf_data.head() ``` -------------------------------- ### Import Libraries and Configure Pandas Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/alternative.ipynb Imports necessary libraries and configures Pandas display options for better data visualization. This setup is common for data analysis tasks. ```python import os import pandas as pd from IPython.core.interactiveshell import InteractiveShell from yahooquery import Ticker import yfinance as yf InteractiveShell.ast_node_interactivity = "all" pd.options.display.float_format = '{:,}'.format pd.options.display.max_columns = None pd.set_option('display.max_rows', 100) ``` -------------------------------- ### Import Screener Class Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/guide/screener.md Import the Screener class from the yahooquery library to begin using its functionalities. ```python from yahooquery import Screener ``` -------------------------------- ### Combine Research and Ticker Classes with Shared Session Source: https://github.com/dpguthrie/yahooquery/blob/master/docs/docs/guide/advanced.md Use this pattern when you need to retrieve research reports and then perform detailed analysis on individual tickers using the same authenticated session. This avoids redundant login operations. ```python from yahooquery import Research, Ticker r = Research(username='username@yahoo.com', password='password') # I want to retrieve last week's Bullish Analyst Report's # for the Financial Services sector df = r.reports( sector='Financial Services', report_date='Last Week', investment_rating='Bullish', report_type='Analyst Report' ) # But now I want to get the data I find relevant and run my own analysis # Using aapl as a default symbol (we will change that later). # But, the important part is passing the current session and crumb # from our Research instance tickers = Ticker('aapl', session=r.session, crumb=r.crumb) # Now, I can loop through the dataframe and retrieve relevant data for # each ticker within the dataframe utilizing the Ticker instance for i, row in df.iterrows(): tickers.symbols = row['Tickers'] data = tickers.p_company_360 # Do something with data # ... # Or, pass all tickers to the Ticker instance ticker_list = df['Tickers'].tolist() ticker_list = list(set(flatten_list(ticker_list))) tickers = Ticker(ticker_list, session=r.session, crumb=r.crumb) data = tickers.p_company_360 # Do something with data # ... ```