CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-yfinance

Download market data from Yahoo! Finance API

Overview
Eval results
Files

search-lookup.mddocs/

Search and Lookup

Search for financial instruments by name or lookup instruments by category with comprehensive filtering and result management. These capabilities enable discovery of investment opportunities and instrument identification.

Capabilities

Search Class

Search for financial instruments, news, and research by query string with configurable result counts and filtering options.

class Search:
    def __init__(self, query: str, max_results: int = 8, news_count: int = 8,
                lists_count: int = 8, include_cb: bool = True,
                include_nav_links: bool = False, include_research: bool = False,
                include_cultural_assets: bool = False, enable_fuzzy_query: bool = False,
                recommended: int = 8, session=None, timeout: int = 30,
                raise_errors: bool = True):
        """
        Create a Search object for finding financial instruments and related content.
        
        Parameters:
        - query: str, search query (company name, ticker, keyword)
        - max_results: int, maximum number of quote results to return
        - news_count: int, maximum number of news articles to return
        - lists_count: int, maximum number of investment lists to return
        - include_cb: bool, include convertible bonds in results
        - include_nav_links: bool, include navigation links
        - include_research: bool, include research reports
        - include_cultural_assets: bool, include cultural/social assets
        - enable_fuzzy_query: bool, enable fuzzy matching for queries
        - recommended: int, number of recommended results
        - session: requests.Session, optional session for HTTP requests
        - timeout: int, request timeout in seconds
        - raise_errors: bool, raise exceptions on errors
        """
    
    def search(self) -> 'Search':
        """
        Execute the search with current parameters.
        
        Returns:
        Search object with populated results
        """
    
    # Result Properties
    quotes: list  # Financial instrument quotes matching search
    news: list  # News articles related to search query
    lists: list  # Investment lists and collections
    research: list  # Research reports and analysis
    nav: list  # Navigation links and related searches
    all: dict  # All results combined in a single dictionary
    response: dict  # Raw API response data

Usage Examples

import yfinance as yf

# Basic company search
search = yf.Search("Apple")
results = search.search()

# Access different result types
quotes = search.quotes  # Stock quotes
news = search.news      # News articles
all_results = search.all  # Everything combined

# Search with custom parameters
search = yf.Search("technology", max_results=20, news_count=15, 
                  include_research=True)
results = search.search()

# Fuzzy search for partial matches
search = yf.Search("Appl", enable_fuzzy_query=True)
results = search.search()

Search Result Structure

Quotes Results (list of dictionaries):

{
    'symbol': 'AAPL',
    'shortname': 'Apple Inc.',
    'longname': 'Apple Inc.',
    'sector': 'Technology',
    'industry': 'Consumer Electronics',
    'exchDisp': 'NASDAQ',
    'typeDisp': 'Equity',
    'market': 'us_market'
}

News Results (list of dictionaries):

{
    'title': 'Apple Reports Strong Q4 Results',
    'publisher': 'Yahoo Finance',
    'link': 'https://...',
    'providerPublishTime': 1234567890,
    'uuid': 'unique-id-string'
}

Lookup Class

Lookup financial instruments by category and type with detailed filtering capabilities.

class Lookup:
    def __init__(self, query: str, session=None, timeout: int = 30, 
                raise_errors: bool = True):
        """
        Create a Lookup object for finding instruments by category.
        
        Parameters:
        - query: str, search query for instrument lookup
        - session: requests.Session, optional session for HTTP requests
        - timeout: int, request timeout in seconds
        - raise_errors: bool, raise exceptions on errors
        """
    
    # Category Methods
    def get_all(self, count: int = 25) -> pd.DataFrame:
        """Get all instrument types matching query."""
    
    def get_stock(self, count: int = 25) -> pd.DataFrame:
        """Get stocks matching query."""
    
    def get_mutualfund(self, count: int = 25) -> pd.DataFrame:
        """Get mutual funds matching query."""
    
    def get_etf(self, count: int = 25) -> pd.DataFrame:
        """Get ETFs matching query."""
    
    def get_index(self, count: int = 25) -> pd.DataFrame:
        """Get indices matching query."""
    
    def get_future(self, count: int = 25) -> pd.DataFrame:
        """Get futures contracts matching query."""
    
    def get_currency(self, count: int = 25) -> pd.DataFrame:
        """Get currency pairs matching query."""
    
    def get_cryptocurrency(self, count: int = 25) -> pd.DataFrame:
        """Get cryptocurrencies matching query."""
    
    # Property Shortcuts (same methods available as properties with default count)
    all: pd.DataFrame  # get_all() with default parameters
    stock: pd.DataFrame  # get_stock() with default parameters
    mutualfund: pd.DataFrame  # get_mutualfund() with default parameters
    etf: pd.DataFrame  # get_etf() with default parameters
    index: pd.DataFrame  # get_index() with default parameters
    future: pd.DataFrame  # get_future() with default parameters
    currency: pd.DataFrame  # get_currency() with default parameters
    cryptocurrency: pd.DataFrame  # get_cryptocurrency() with default parameters

Usage Examples

# Basic lookup
lookup = yf.Lookup("technology")

# Get different instrument types
stocks = lookup.get_stock(count=20)
etfs = lookup.get_etf(count=10)
all_instruments = lookup.get_all(count=50)

# Use property shortcuts
tech_stocks = lookup.stock  # Uses default count=25
tech_etfs = lookup.etf

# Sector-specific lookups
energy_lookup = yf.Lookup("energy")
energy_stocks = energy_lookup.get_stock(count=30)
energy_etfs = energy_lookup.get_etf(count=15)

# Geographic lookups
japan_lookup = yf.Lookup("japan")
japanese_stocks = japan_lookup.get_stock()
japanese_indices = japan_lookup.get_index()

# Currency and crypto lookups
crypto_lookup = yf.Lookup("bitcoin")
crypto_results = crypto_lookup.get_cryptocurrency()

fx_lookup = yf.Lookup("eur")
currency_pairs = fx_lookup.get_currency()

Lookup Result Structure

Lookup methods return pandas DataFrames with instrument details:

DataFrame Columns:

  • symbol: Ticker symbol
  • shortname: Short display name
  • longname: Full company/instrument name
  • sector: Business sector (for stocks)
  • industry: Industry classification
  • exchange: Trading exchange
  • market: Market classification
  • type: Instrument type (stock, etf, etc.)

Advanced Search Patterns

Multi-Category Discovery

def comprehensive_search(query, max_count=10):
    """Perform comprehensive search across all categories."""
    
    # Search for general matches
    search = yf.Search(query, max_results=max_count)
    search_results = search.search()
    
    # Lookup by category
    lookup = yf.Lookup(query)
    
    results = {
        'search_quotes': search.quotes,
        'search_news': search.news,
        'stocks': lookup.get_stock(count=max_count),
        'etfs': lookup.get_etf(count=max_count),
        'mutual_funds': lookup.get_mutualfund(count=max_count),
        'indices': lookup.get_index(count=max_count)
    }
    
    return results

# Usage
tech_results = comprehensive_search("artificial intelligence", max_count=15)

Sector Analysis Discovery

def analyze_sector(sector_name):
    """Discover and analyze instruments in a specific sector."""
    
    lookup = yf.Lookup(sector_name)
    
    # Get different instrument types
    sector_stocks = lookup.get_stock(count=50)
    sector_etfs = lookup.get_etf(count=20)
    
    # Filter and analyze results
    large_cap_stocks = sector_stocks[sector_stocks['market'].str.contains('large', na=False)]
    
    return {
        'stocks': sector_stocks,
        'etfs': sector_etfs,
        'large_cap': large_cap_stocks,
        'total_instruments': len(sector_stocks) + len(sector_etfs)
    }

# Usage
healthcare_analysis = analyze_sector("healthcare")

Investment Theme Discovery

def discover_investment_theme(theme, include_news=True):
    """Discover investment opportunities around a specific theme."""
    
    # Search for theme-related instruments and news
    search = yf.Search(theme, max_results=25, news_count=20 if include_news else 0)
    results = search.search()
    
    # Lookup instruments by theme
    lookup = yf.Lookup(theme)
    
    theme_data = {
        'instruments': results.quotes,
        'stocks': lookup.get_stock(count=30),
        'etfs': lookup.get_etf(count=15),
        'news': results.news if include_news else [],
        'total_matches': len(results.quotes)
    }
    
    return theme_data

# Usage for various themes
esg_investments = discover_investment_theme("ESG")
ai_investments = discover_investment_theme("artificial intelligence")
renewable_energy = discover_investment_theme("renewable energy")

Geographic Market Discovery

def explore_geographic_market(region):
    """Explore investment opportunities in specific geographic regions."""
    
    lookup = yf.Lookup(region)
    
    # Get various instrument types for the region
    regional_data = {
        'stocks': lookup.get_stock(count=40),
        'etfs': lookup.get_etf(count=20),
        'indices': lookup.get_index(count=10),
        'currencies': lookup.get_currency(count=10)
    }
    
    # Search for region-specific news
    search = yf.Search(region, max_results=10, news_count=15)
    search_results = search.search()
    regional_data['news'] = search_results.news
    
    return regional_data

# Usage
emerging_markets = explore_geographic_market("emerging markets")
europe_investments = explore_geographic_market("europe")
asia_pacific = explore_geographic_market("asia pacific")

Error Handling and Best Practices

Handling Empty Results

def safe_search(query, fallback_queries=None):
    """Perform search with fallback options for empty results."""
    
    search = yf.Search(query)
    results = search.search()
    
    if not results.quotes and fallback_queries:
        for fallback in fallback_queries:
            search = yf.Search(fallback, enable_fuzzy_query=True)
            results = search.search()
            if results.quotes:
                break
    
    return results

# Usage with fallbacks
results = safe_search("AAPL", fallback_queries=["Apple", "Apple Inc"])

Validating Search Results

def validate_and_filter_results(search_results, min_market_cap=None):
    """Validate and filter search results based on criteria."""
    
    valid_quotes = []
    for quote in search_results.quotes:
        # Basic validation
        if 'symbol' in quote and 'shortname' in quote:
            # Additional filtering can be added here
            if min_market_cap is None or quote.get('marketCap', 0) >= min_market_cap:
                valid_quotes.append(quote)
    
    return valid_quotes

# Usage
search = yf.Search("technology")
results = search.search()
large_cap_only = validate_and_filter_results(results, min_market_cap=10_000_000_000)

Batch Lookup Operations

def batch_lookup_by_categories(queries, categories=['stock', 'etf']):
    """Perform batch lookups across multiple queries and categories."""
    
    all_results = {}
    
    for query in queries:
        lookup = yf.Lookup(query)
        query_results = {}
        
        for category in categories:
            method = getattr(lookup, f'get_{category}', None)
            if method:
                try:
                    query_results[category] = method(count=20)
                except Exception as e:
                    print(f"Error in {category} lookup for {query}: {e}")
                    query_results[category] = pd.DataFrame()
        
        all_results[query] = query_results
    
    return all_results

# Usage
sector_queries = ["technology", "healthcare", "finance", "energy"]
sector_data = batch_lookup_by_categories(sector_queries, ['stock', 'etf', 'mutualfund'])

Integration with Other yfinance Features

Search to Ticker Analysis Pipeline

def search_to_analysis_pipeline(query, top_n=5):
    """Complete pipeline from search to detailed analysis."""
    
    # Step 1: Search for instruments
    search = yf.Search(query, max_results=20)
    results = search.search()
    
    # Step 2: Select top instruments
    top_symbols = [quote['symbol'] for quote in results.quotes[:top_n]]
    
    # Step 3: Detailed analysis
    analysis_results = {}
    for symbol in top_symbols:
        ticker = yf.Ticker(symbol)
        analysis_results[symbol] = {
            'info': ticker.info,
            'history': ticker.history(period="1mo"),
            'recommendations': ticker.recommendations
        }
    
    return analysis_results

# Usage
ai_analysis = search_to_analysis_pipeline("artificial intelligence", top_n=3)

Building Watchlists from Search Results

def create_watchlist_from_search(query, criteria=None):
    """Create a watchlist from search results based on criteria."""
    
    search = yf.Search(query, max_results=50)
    results = search.search()
    
    watchlist = []
    for quote in results.quotes:
        symbol = quote['symbol']
        
        # Apply criteria if specified
        if criteria is None or criteria(quote):
            watchlist.append({
                'symbol': symbol,
                'name': quote.get('shortname', ''),
                'sector': quote.get('sector', ''),
                'exchange': quote.get('exchDisp', '')
            })
    
    return watchlist

# Usage with criteria
def large_cap_tech(quote):
    return (quote.get('sector') == 'Technology' and 
            quote.get('marketCap', 0) > 1_000_000_000)

tech_watchlist = create_watchlist_from_search("technology", criteria=large_cap_tech)

Install with Tessl CLI

npx tessl i tessl/pypi-yfinance

docs

bulk-data.md

config-utils.md

index.md

live-streaming.md

market-sector.md

screening.md

search-lookup.md

ticker-data.md

tile.json