0
# Search and Lookup
1
2
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.
3
4
## Capabilities
5
6
### Search Class
7
8
Search for financial instruments, news, and research by query string with configurable result counts and filtering options.
9
10
```python { .api }
11
class Search:
12
def __init__(self, query: str, max_results: int = 8, news_count: int = 8,
13
lists_count: int = 8, include_cb: bool = True,
14
include_nav_links: bool = False, include_research: bool = False,
15
include_cultural_assets: bool = False, enable_fuzzy_query: bool = False,
16
recommended: int = 8, session=None, timeout: int = 30,
17
raise_errors: bool = True):
18
"""
19
Create a Search object for finding financial instruments and related content.
20
21
Parameters:
22
- query: str, search query (company name, ticker, keyword)
23
- max_results: int, maximum number of quote results to return
24
- news_count: int, maximum number of news articles to return
25
- lists_count: int, maximum number of investment lists to return
26
- include_cb: bool, include convertible bonds in results
27
- include_nav_links: bool, include navigation links
28
- include_research: bool, include research reports
29
- include_cultural_assets: bool, include cultural/social assets
30
- enable_fuzzy_query: bool, enable fuzzy matching for queries
31
- recommended: int, number of recommended results
32
- session: requests.Session, optional session for HTTP requests
33
- timeout: int, request timeout in seconds
34
- raise_errors: bool, raise exceptions on errors
35
"""
36
37
def search(self) -> 'Search':
38
"""
39
Execute the search with current parameters.
40
41
Returns:
42
Search object with populated results
43
"""
44
45
# Result Properties
46
quotes: list # Financial instrument quotes matching search
47
news: list # News articles related to search query
48
lists: list # Investment lists and collections
49
research: list # Research reports and analysis
50
nav: list # Navigation links and related searches
51
all: dict # All results combined in a single dictionary
52
response: dict # Raw API response data
53
```
54
55
#### Usage Examples
56
57
```python
58
import yfinance as yf
59
60
# Basic company search
61
search = yf.Search("Apple")
62
results = search.search()
63
64
# Access different result types
65
quotes = search.quotes # Stock quotes
66
news = search.news # News articles
67
all_results = search.all # Everything combined
68
69
# Search with custom parameters
70
search = yf.Search("technology", max_results=20, news_count=15,
71
include_research=True)
72
results = search.search()
73
74
# Fuzzy search for partial matches
75
search = yf.Search("Appl", enable_fuzzy_query=True)
76
results = search.search()
77
```
78
79
#### Search Result Structure
80
81
**Quotes Results** (list of dictionaries):
82
```python
83
{
84
'symbol': 'AAPL',
85
'shortname': 'Apple Inc.',
86
'longname': 'Apple Inc.',
87
'sector': 'Technology',
88
'industry': 'Consumer Electronics',
89
'exchDisp': 'NASDAQ',
90
'typeDisp': 'Equity',
91
'market': 'us_market'
92
}
93
```
94
95
**News Results** (list of dictionaries):
96
```python
97
{
98
'title': 'Apple Reports Strong Q4 Results',
99
'publisher': 'Yahoo Finance',
100
'link': 'https://...',
101
'providerPublishTime': 1234567890,
102
'uuid': 'unique-id-string'
103
}
104
```
105
106
### Lookup Class
107
108
Lookup financial instruments by category and type with detailed filtering capabilities.
109
110
```python { .api }
111
class Lookup:
112
def __init__(self, query: str, session=None, timeout: int = 30,
113
raise_errors: bool = True):
114
"""
115
Create a Lookup object for finding instruments by category.
116
117
Parameters:
118
- query: str, search query for instrument lookup
119
- session: requests.Session, optional session for HTTP requests
120
- timeout: int, request timeout in seconds
121
- raise_errors: bool, raise exceptions on errors
122
"""
123
124
# Category Methods
125
def get_all(self, count: int = 25) -> pd.DataFrame:
126
"""Get all instrument types matching query."""
127
128
def get_stock(self, count: int = 25) -> pd.DataFrame:
129
"""Get stocks matching query."""
130
131
def get_mutualfund(self, count: int = 25) -> pd.DataFrame:
132
"""Get mutual funds matching query."""
133
134
def get_etf(self, count: int = 25) -> pd.DataFrame:
135
"""Get ETFs matching query."""
136
137
def get_index(self, count: int = 25) -> pd.DataFrame:
138
"""Get indices matching query."""
139
140
def get_future(self, count: int = 25) -> pd.DataFrame:
141
"""Get futures contracts matching query."""
142
143
def get_currency(self, count: int = 25) -> pd.DataFrame:
144
"""Get currency pairs matching query."""
145
146
def get_cryptocurrency(self, count: int = 25) -> pd.DataFrame:
147
"""Get cryptocurrencies matching query."""
148
149
# Property Shortcuts (same methods available as properties with default count)
150
all: pd.DataFrame # get_all() with default parameters
151
stock: pd.DataFrame # get_stock() with default parameters
152
mutualfund: pd.DataFrame # get_mutualfund() with default parameters
153
etf: pd.DataFrame # get_etf() with default parameters
154
index: pd.DataFrame # get_index() with default parameters
155
future: pd.DataFrame # get_future() with default parameters
156
currency: pd.DataFrame # get_currency() with default parameters
157
cryptocurrency: pd.DataFrame # get_cryptocurrency() with default parameters
158
```
159
160
#### Usage Examples
161
162
```python
163
# Basic lookup
164
lookup = yf.Lookup("technology")
165
166
# Get different instrument types
167
stocks = lookup.get_stock(count=20)
168
etfs = lookup.get_etf(count=10)
169
all_instruments = lookup.get_all(count=50)
170
171
# Use property shortcuts
172
tech_stocks = lookup.stock # Uses default count=25
173
tech_etfs = lookup.etf
174
175
# Sector-specific lookups
176
energy_lookup = yf.Lookup("energy")
177
energy_stocks = energy_lookup.get_stock(count=30)
178
energy_etfs = energy_lookup.get_etf(count=15)
179
180
# Geographic lookups
181
japan_lookup = yf.Lookup("japan")
182
japanese_stocks = japan_lookup.get_stock()
183
japanese_indices = japan_lookup.get_index()
184
185
# Currency and crypto lookups
186
crypto_lookup = yf.Lookup("bitcoin")
187
crypto_results = crypto_lookup.get_cryptocurrency()
188
189
fx_lookup = yf.Lookup("eur")
190
currency_pairs = fx_lookup.get_currency()
191
```
192
193
#### Lookup Result Structure
194
195
Lookup methods return pandas DataFrames with instrument details:
196
197
**DataFrame Columns**:
198
- `symbol`: Ticker symbol
199
- `shortname`: Short display name
200
- `longname`: Full company/instrument name
201
- `sector`: Business sector (for stocks)
202
- `industry`: Industry classification
203
- `exchange`: Trading exchange
204
- `market`: Market classification
205
- `type`: Instrument type (stock, etf, etc.)
206
207
## Advanced Search Patterns
208
209
### Multi-Category Discovery
210
211
```python
212
def comprehensive_search(query, max_count=10):
213
"""Perform comprehensive search across all categories."""
214
215
# Search for general matches
216
search = yf.Search(query, max_results=max_count)
217
search_results = search.search()
218
219
# Lookup by category
220
lookup = yf.Lookup(query)
221
222
results = {
223
'search_quotes': search.quotes,
224
'search_news': search.news,
225
'stocks': lookup.get_stock(count=max_count),
226
'etfs': lookup.get_etf(count=max_count),
227
'mutual_funds': lookup.get_mutualfund(count=max_count),
228
'indices': lookup.get_index(count=max_count)
229
}
230
231
return results
232
233
# Usage
234
tech_results = comprehensive_search("artificial intelligence", max_count=15)
235
```
236
237
### Sector Analysis Discovery
238
239
```python
240
def analyze_sector(sector_name):
241
"""Discover and analyze instruments in a specific sector."""
242
243
lookup = yf.Lookup(sector_name)
244
245
# Get different instrument types
246
sector_stocks = lookup.get_stock(count=50)
247
sector_etfs = lookup.get_etf(count=20)
248
249
# Filter and analyze results
250
large_cap_stocks = sector_stocks[sector_stocks['market'].str.contains('large', na=False)]
251
252
return {
253
'stocks': sector_stocks,
254
'etfs': sector_etfs,
255
'large_cap': large_cap_stocks,
256
'total_instruments': len(sector_stocks) + len(sector_etfs)
257
}
258
259
# Usage
260
healthcare_analysis = analyze_sector("healthcare")
261
```
262
263
### Investment Theme Discovery
264
265
```python
266
def discover_investment_theme(theme, include_news=True):
267
"""Discover investment opportunities around a specific theme."""
268
269
# Search for theme-related instruments and news
270
search = yf.Search(theme, max_results=25, news_count=20 if include_news else 0)
271
results = search.search()
272
273
# Lookup instruments by theme
274
lookup = yf.Lookup(theme)
275
276
theme_data = {
277
'instruments': results.quotes,
278
'stocks': lookup.get_stock(count=30),
279
'etfs': lookup.get_etf(count=15),
280
'news': results.news if include_news else [],
281
'total_matches': len(results.quotes)
282
}
283
284
return theme_data
285
286
# Usage for various themes
287
esg_investments = discover_investment_theme("ESG")
288
ai_investments = discover_investment_theme("artificial intelligence")
289
renewable_energy = discover_investment_theme("renewable energy")
290
```
291
292
### Geographic Market Discovery
293
294
```python
295
def explore_geographic_market(region):
296
"""Explore investment opportunities in specific geographic regions."""
297
298
lookup = yf.Lookup(region)
299
300
# Get various instrument types for the region
301
regional_data = {
302
'stocks': lookup.get_stock(count=40),
303
'etfs': lookup.get_etf(count=20),
304
'indices': lookup.get_index(count=10),
305
'currencies': lookup.get_currency(count=10)
306
}
307
308
# Search for region-specific news
309
search = yf.Search(region, max_results=10, news_count=15)
310
search_results = search.search()
311
regional_data['news'] = search_results.news
312
313
return regional_data
314
315
# Usage
316
emerging_markets = explore_geographic_market("emerging markets")
317
europe_investments = explore_geographic_market("europe")
318
asia_pacific = explore_geographic_market("asia pacific")
319
```
320
321
## Error Handling and Best Practices
322
323
### Handling Empty Results
324
325
```python
326
def safe_search(query, fallback_queries=None):
327
"""Perform search with fallback options for empty results."""
328
329
search = yf.Search(query)
330
results = search.search()
331
332
if not results.quotes and fallback_queries:
333
for fallback in fallback_queries:
334
search = yf.Search(fallback, enable_fuzzy_query=True)
335
results = search.search()
336
if results.quotes:
337
break
338
339
return results
340
341
# Usage with fallbacks
342
results = safe_search("AAPL", fallback_queries=["Apple", "Apple Inc"])
343
```
344
345
### Validating Search Results
346
347
```python
348
def validate_and_filter_results(search_results, min_market_cap=None):
349
"""Validate and filter search results based on criteria."""
350
351
valid_quotes = []
352
for quote in search_results.quotes:
353
# Basic validation
354
if 'symbol' in quote and 'shortname' in quote:
355
# Additional filtering can be added here
356
if min_market_cap is None or quote.get('marketCap', 0) >= min_market_cap:
357
valid_quotes.append(quote)
358
359
return valid_quotes
360
361
# Usage
362
search = yf.Search("technology")
363
results = search.search()
364
large_cap_only = validate_and_filter_results(results, min_market_cap=10_000_000_000)
365
```
366
367
### Batch Lookup Operations
368
369
```python
370
def batch_lookup_by_categories(queries, categories=['stock', 'etf']):
371
"""Perform batch lookups across multiple queries and categories."""
372
373
all_results = {}
374
375
for query in queries:
376
lookup = yf.Lookup(query)
377
query_results = {}
378
379
for category in categories:
380
method = getattr(lookup, f'get_{category}', None)
381
if method:
382
try:
383
query_results[category] = method(count=20)
384
except Exception as e:
385
print(f"Error in {category} lookup for {query}: {e}")
386
query_results[category] = pd.DataFrame()
387
388
all_results[query] = query_results
389
390
return all_results
391
392
# Usage
393
sector_queries = ["technology", "healthcare", "finance", "energy"]
394
sector_data = batch_lookup_by_categories(sector_queries, ['stock', 'etf', 'mutualfund'])
395
```
396
397
## Integration with Other yfinance Features
398
399
### Search to Ticker Analysis Pipeline
400
401
```python
402
def search_to_analysis_pipeline(query, top_n=5):
403
"""Complete pipeline from search to detailed analysis."""
404
405
# Step 1: Search for instruments
406
search = yf.Search(query, max_results=20)
407
results = search.search()
408
409
# Step 2: Select top instruments
410
top_symbols = [quote['symbol'] for quote in results.quotes[:top_n]]
411
412
# Step 3: Detailed analysis
413
analysis_results = {}
414
for symbol in top_symbols:
415
ticker = yf.Ticker(symbol)
416
analysis_results[symbol] = {
417
'info': ticker.info,
418
'history': ticker.history(period="1mo"),
419
'recommendations': ticker.recommendations
420
}
421
422
return analysis_results
423
424
# Usage
425
ai_analysis = search_to_analysis_pipeline("artificial intelligence", top_n=3)
426
```
427
428
### Building Watchlists from Search Results
429
430
```python
431
def create_watchlist_from_search(query, criteria=None):
432
"""Create a watchlist from search results based on criteria."""
433
434
search = yf.Search(query, max_results=50)
435
results = search.search()
436
437
watchlist = []
438
for quote in results.quotes:
439
symbol = quote['symbol']
440
441
# Apply criteria if specified
442
if criteria is None or criteria(quote):
443
watchlist.append({
444
'symbol': symbol,
445
'name': quote.get('shortname', ''),
446
'sector': quote.get('sector', ''),
447
'exchange': quote.get('exchDisp', '')
448
})
449
450
return watchlist
451
452
# Usage with criteria
453
def large_cap_tech(quote):
454
return (quote.get('sector') == 'Technology' and
455
quote.get('marketCap', 0) > 1_000_000_000)
456
457
tech_watchlist = create_watchlist_from_search("technology", criteria=large_cap_tech)
458
```