Download market data from Yahoo! Finance API
npx @tessl/cli install tessl/pypi-yfinance@0.2.00
# yfinance
1
2
A Python library that provides a Pythonic way to fetch financial and market data from Yahoo! Finance's API. It offers comprehensive functionality for downloading historical market data, real-time quotes, financial statements, and other financial information for stocks, ETFs, mutual funds, currencies, and cryptocurrencies.
3
4
## Package Information
5
6
- **Package Name**: yfinance
7
- **Language**: Python
8
- **Installation**: `pip install yfinance`
9
10
## Core Imports
11
12
```python
13
import yfinance as yf
14
```
15
16
For specific components:
17
18
```python
19
from yfinance import Ticker, download, Search, Lookup
20
from yfinance import WebSocket, AsyncWebSocket
21
from yfinance import Market, Sector, Industry
22
from yfinance import EquityQuery, FundQuery, screen
23
```
24
25
## Basic Usage
26
27
```python
28
import yfinance as yf
29
30
# Single ticker data
31
ticker = yf.Ticker("AAPL")
32
info = ticker.info
33
history = ticker.history(period="1mo")
34
35
# Multiple ticker download
36
data = yf.download(["AAPL", "GOOGL", "MSFT"], period="1mo")
37
38
# Search for companies
39
search = yf.Search("Apple")
40
quotes = search.quotes
41
42
# Real-time streaming
43
def handle_message(msg):
44
print(msg)
45
46
ws = yf.WebSocket()
47
ws.subscribe(["AAPL", "GOOGL"])
48
ws.listen(handle_message)
49
```
50
51
## Architecture
52
53
yfinance provides multiple access patterns:
54
55
- **Individual Ticker Access**: `Ticker` class for detailed single-symbol analysis
56
- **Bulk Data Operations**: `download()` function and `Tickers` class for multi-symbol operations
57
- **Real-time Streaming**: `WebSocket` and `AsyncWebSocket` for live data feeds
58
- **Search & Discovery**: `Search` and `Lookup` classes for finding financial instruments
59
- **Market Intelligence**: `Market`, `Sector`, and `Industry` classes for broader market analysis
60
- **Custom Screening**: `EquityQuery`, `FundQuery`, and `screen()` for filtering instruments
61
62
The library is built around Yahoo Finance's public APIs and provides comprehensive error handling, data caching, and rate limiting.
63
64
## Capabilities
65
66
### Single Ticker Data Access
67
68
Comprehensive data access for individual financial instruments including historical prices, financial statements, ownership data, analyst recommendations, options chains, and company information.
69
70
```python { .api }
71
class Ticker:
72
def __init__(self, ticker: str, session=None, proxy=None): ...
73
def history(self, period: str = "1mo", interval: str = "1d",
74
start=None, end=None, **kwargs) -> pd.DataFrame: ...
75
def option_chain(self, date=None, tz=None) -> namedtuple: ...
76
77
# Properties for financial data
78
info: dict
79
financials: pd.DataFrame
80
balance_sheet: pd.DataFrame
81
cash_flow: pd.DataFrame
82
earnings: pd.DataFrame
83
recommendations: pd.DataFrame
84
options: tuple
85
```
86
87
[Single Ticker Data Access](./ticker-data.md)
88
89
### Bulk Data Operations
90
91
Efficient downloading and management of multiple financial instruments with threading support and various data formatting options.
92
93
```python { .api }
94
def download(tickers, start=None, end=None, period=None, interval="1d",
95
group_by='column', auto_adjust=None, threads=True, **kwargs) -> pd.DataFrame: ...
96
97
class Tickers:
98
def __init__(self, tickers, session=None): ...
99
def history(self, **kwargs) -> pd.DataFrame: ...
100
def news(self) -> dict: ...
101
```
102
103
[Bulk Data Operations](./bulk-data.md)
104
105
### Search and Lookup
106
107
Search for financial instruments by name or lookup instruments by category with comprehensive filtering and result management.
108
109
```python { .api }
110
class Search:
111
def __init__(self, query: str, max_results: int = 8, **kwargs): ...
112
def search(self) -> 'Search': ...
113
114
# Properties
115
quotes: list
116
news: list
117
all: dict
118
119
class Lookup:
120
def __init__(self, query: str, **kwargs): ...
121
def get_stock(self, count: int = 25) -> pd.DataFrame: ...
122
def get_etf(self, count: int = 25) -> pd.DataFrame: ...
123
def get_mutualfund(self, count: int = 25) -> pd.DataFrame: ...
124
```
125
126
[Search and Lookup](./search-lookup.md)
127
128
### Real-time Data Streaming
129
130
Live financial data streaming using WebSocket connections with both synchronous and asynchronous support.
131
132
```python { .api }
133
class WebSocket:
134
def __init__(self, url: str = "wss://streamer.finance.yahoo.com/?version=2",
135
verbose: bool = True): ...
136
def subscribe(self, symbols: Union[str, List[str]]): ...
137
def listen(self, message_handler: Optional[Callable] = None): ...
138
def close(self): ...
139
140
class AsyncWebSocket:
141
async def subscribe(self, symbols: Union[str, List[str]]): ...
142
async def listen(self, message_handler: Optional[Callable] = None): ...
143
```
144
145
[Real-time Data Streaming](./live-streaming.md)
146
147
### Market and Sector Analysis
148
149
Market status information, sector performance data, and industry-level analysis for broader market intelligence.
150
151
```python { .api }
152
class Market:
153
def __init__(self, market: str, session=None, timeout: int = 30): ...
154
155
# Properties
156
status: dict
157
summary: dict
158
159
class Sector:
160
def __init__(self, key: str, session=None): ...
161
162
# Properties
163
top_etfs: Dict[str, str]
164
top_mutual_funds: Dict[str, str]
165
industries: pd.DataFrame
166
167
class Industry:
168
def __init__(self, key: str, session=None): ...
169
170
# Properties
171
top_performing_companies: pd.DataFrame
172
top_growth_companies: pd.DataFrame
173
```
174
175
[Market and Sector Analysis](./market-sector.md)
176
177
### Custom Screening
178
179
Build custom queries to screen and filter financial instruments based on various criteria with predefined screening options.
180
181
```python { .api }
182
class EquityQuery:
183
def __init__(self, operator: str, operand: list): ...
184
185
class FundQuery:
186
def __init__(self, operator: str, operand: list): ...
187
188
def screen(query: Union[str, EquityQuery, FundQuery],
189
size: int = None, sortField: str = None, **kwargs) -> dict: ...
190
191
PREDEFINED_SCREENER_QUERIES: Dict[str, str]
192
```
193
194
[Custom Screening](./screening.md)
195
196
### Configuration and Utilities
197
198
Global configuration options, debugging utilities, and cache management for optimal performance and troubleshooting.
199
200
```python { .api }
201
def set_config(proxy=None): ...
202
def enable_debug_mode(): ...
203
def set_tz_cache_location(cache_dir: str): ...
204
```
205
206
[Configuration and Utilities](./config-utils.md)
207
208
## Common Data Formats
209
210
- **Historical Data**: pandas DataFrame with OHLCV columns and datetime index
211
- **Financial Statements**: pandas DataFrame with financial metrics as columns and periods as index
212
- **Company Information**: Dictionary with key-value pairs for company metadata
213
- **Options Chains**: Named tuple with `.calls`, `.puts`, and `.underlying` attributes
214
- **News Articles**: List of dictionaries with article metadata and content
215
- **Search Results**: List of dictionaries with instrument metadata
216
217
## Error Handling
218
219
yfinance includes comprehensive error handling for common scenarios:
220
- Invalid ticker symbols
221
- Network connectivity issues
222
- API rate limiting
223
- Data unavailability
224
- Malformed requests
225
226
Most methods will return empty DataFrames or None values rather than raising exceptions, allowing for graceful handling of missing data.