0
# Market Data Access
1
2
Historical and real-time market data for stocks and cryptocurrencies including bars, trades, quotes, snapshots, and news. Supports multiple data feeds and provides pandas DataFrame integration for analysis workflows.
3
4
## Capabilities
5
6
### Historical Bars
7
8
Retrieve historical price bars (OHLCV data) with customizable time frames and data feeds.
9
10
```python { .api }
11
def get_bars(
12
symbol: Union[str, List[str]],
13
timeframe: TimeFrame,
14
start: str,
15
end: str,
16
adjustment: str = "raw",
17
limit: int = None,
18
feed: str = None,
19
asof: str = None,
20
sort: Sort = None
21
) -> BarsV2:
22
"""Get historical bars for a symbol."""
23
24
def get_bars_iter(
25
symbol: Union[str, List[str]],
26
timeframe: TimeFrame,
27
start: str,
28
end: str,
29
adjustment: str = "raw",
30
limit: int = None,
31
feed: str = None,
32
asof: str = None,
33
sort: Sort = None,
34
raw: bool = False
35
) -> Iterator[Union[BarV2, dict]]:
36
"""Get historical bars as an iterator."""
37
```
38
39
**Usage Examples:**
40
41
```python
42
from alpaca_trade_api import TimeFrame
43
44
# Get daily bars for the last month
45
bars = api.get_bars(
46
'AAPL',
47
TimeFrame.Day,
48
'2023-01-01',
49
'2023-01-31'
50
)
51
52
# Convert to pandas DataFrame
53
df = bars.df
54
print(f"Retrieved {len(df)} bars")
55
print(df.head())
56
57
# Get minute bars with iterator for large datasets
58
for bar in api.get_bars_iter('TSLA', TimeFrame.Minute, '2023-01-01', '2023-01-02'):
59
print(f"{bar.timestamp}: O={bar.open}, H={bar.high}, L={bar.low}, C={bar.close}, V={bar.volume}")
60
```
61
62
### Historical Trades
63
64
Access individual trade execution data with detailed trade information.
65
66
```python { .api }
67
def get_trades(
68
symbol: Union[str, List[str]],
69
start: str,
70
end: str,
71
limit: int = None,
72
feed: str = None,
73
asof: str = None,
74
sort: Sort = None
75
) -> TradesV2:
76
"""Get historical trades for a symbol."""
77
78
def get_trades_iter(
79
symbol: Union[str, List[str]],
80
start: str,
81
end: str,
82
limit: int = None,
83
feed: str = None,
84
asof: str = None,
85
sort: Sort = None,
86
raw: bool = False
87
) -> Iterator[Union[TradeV2, dict]]:
88
"""Get historical trades as an iterator."""
89
```
90
91
**Usage Examples:**
92
93
```python
94
# Get trades for a specific day
95
trades = api.get_trades('AAPL', '2023-01-15', '2023-01-16')
96
df = trades.df
97
print(f"Total trades: {len(df)}")
98
print(f"Volume weighted average price: {(df['price'] * df['size']).sum() / df['size'].sum()}")
99
100
# Process trades with iterator
101
total_volume = 0
102
for trade in api.get_trades_iter('TSLA', '2023-01-15T09:30:00', '2023-01-15T16:00:00'):
103
total_volume += trade.size
104
if trade.price > 200:
105
print(f"Large trade: {trade.size} shares at ${trade.price}")
106
```
107
108
### Historical Quotes
109
110
Retrieve bid/ask quote data for market analysis and spread calculations.
111
112
```python { .api }
113
def get_quotes(
114
symbol: Union[str, List[str]],
115
start: str,
116
end: str,
117
limit: int = None,
118
feed: str = None,
119
asof: str = None,
120
sort: Sort = None
121
) -> QuotesV2:
122
"""Get historical quotes for a symbol."""
123
124
def get_quotes_iter(
125
symbol: Union[str, List[str]],
126
start: str,
127
end: str,
128
limit: int = None,
129
feed: str = None,
130
asof: str = None,
131
sort: Sort = None,
132
raw: bool = False
133
) -> Iterator[Union[QuoteV2, dict]]:
134
"""Get historical quotes as an iterator."""
135
```
136
137
**Usage Examples:**
138
139
```python
140
# Get quotes and analyze bid-ask spreads
141
quotes = api.get_quotes('AAPL', '2023-01-15T09:30:00', '2023-01-15T16:00:00')
142
df = quotes.df
143
df['spread'] = df['ask_price'] - df['bid_price']
144
df['spread_bps'] = (df['spread'] / df['bid_price']) * 10000
145
print(f"Average spread: {df['spread_bps'].mean():.2f} basis points")
146
```
147
148
### Latest Market Data
149
150
Get the most recent market data for real-time analysis and decision making.
151
152
```python { .api }
153
def get_latest_bar(symbol: str, feed: str = None) -> BarV2:
154
"""Get the latest bar for a symbol."""
155
156
def get_latest_bars(symbols: List[str], feed: str = None) -> LatestBarsV2:
157
"""Get latest bars for multiple symbols."""
158
159
def get_latest_trade(symbol: str, feed: str = None) -> TradeV2:
160
"""Get the latest trade for a symbol."""
161
162
def get_latest_trades(symbols: List[str], feed: str = None) -> LatestTradesV2:
163
"""Get latest trades for multiple symbols."""
164
165
def get_latest_quote(symbol: str, feed: str = None) -> QuoteV2:
166
"""Get the latest quote for a symbol."""
167
168
def get_latest_quotes(symbols: List[str], feed: str = None) -> LatestQuotesV2:
169
"""Get latest quotes for multiple symbols."""
170
```
171
172
**Usage Examples:**
173
174
```python
175
# Get latest data for multiple symbols
176
symbols = ['AAPL', 'TSLA', 'GOOGL', 'MSFT']
177
latest_bars = api.get_latest_bars(symbols)
178
for symbol, bar in latest_bars.items():
179
print(f"{symbol}: ${bar.close} (Volume: {bar.volume:,})")
180
181
# Get current quote data
182
quote = api.get_latest_quote('AAPL')
183
print(f"AAPL Bid: ${quote.bid_price} x {quote.bid_size}")
184
print(f"AAPL Ask: ${quote.ask_price} x {quote.ask_size}")
185
print(f"Spread: ${quote.ask_price - quote.bid_price:.2f}")
186
```
187
188
### Market Snapshots
189
190
Comprehensive market snapshots containing latest trade, quote, and bar data in a single request.
191
192
```python { .api }
193
def get_snapshot(symbol: str, feed: str = None) -> SnapshotV2:
194
"""Get a market snapshot for a symbol."""
195
196
def get_snapshots(symbols: List[str], feed: str = None) -> SnapshotsV2:
197
"""Get market snapshots for multiple symbols."""
198
```
199
200
**Usage Examples:**
201
202
```python
203
# Get comprehensive market data
204
snapshot = api.get_snapshot('AAPL')
205
print(f"Latest Trade: ${snapshot.latest_trade.price} at {snapshot.latest_trade.timestamp}")
206
print(f"Latest Quote: ${snapshot.latest_quote.bid_price} x ${snapshot.latest_quote.ask_price}")
207
print(f"Daily Bar: O=${snapshot.daily_bar.open} H=${snapshot.daily_bar.high} L=${snapshot.daily_bar.low} C=${snapshot.daily_bar.close}")
208
209
# Get snapshots for portfolio monitoring
210
portfolio_symbols = ['AAPL', 'TSLA', 'GOOGL']
211
snapshots = api.get_snapshots(portfolio_symbols)
212
for symbol, snapshot in snapshots.items():
213
day_change = snapshot.daily_bar.close - snapshot.prev_daily_bar.close
214
day_change_pct = (day_change / snapshot.prev_daily_bar.close) * 100
215
print(f"{symbol}: ${snapshot.daily_bar.close} ({day_change_pct:+.2f}%)")
216
```
217
218
### News Data
219
220
Access financial news articles with symbol filtering and content options.
221
222
```python { .api }
223
def get_news(
224
symbol: Union[str, List[str]] = None,
225
start: str = None,
226
end: str = None,
227
limit: int = 10,
228
sort: Sort = Sort.Desc,
229
include_content: bool = False,
230
exclude_contentless: bool = False
231
) -> NewsListV2:
232
"""Get news articles."""
233
234
def get_news_iter(
235
symbol: Union[str, List[str]] = None,
236
start: str = None,
237
end: str = None,
238
limit: int = 10,
239
sort: Sort = Sort.Desc,
240
include_content: bool = False,
241
exclude_contentless: bool = False,
242
raw: bool = False
243
) -> Iterator[Union[NewsV2, dict]]:
244
"""Get news articles as an iterator."""
245
```
246
247
**Usage Examples:**
248
249
```python
250
# Get recent news for a symbol
251
news = api.get_news('AAPL', limit=10)
252
for article in news:
253
print(f"{article.created_at}: {article.headline}")
254
print(f"Summary: {article.summary}")
255
print(f"URL: {article.url}")
256
print("---")
257
258
# Get market-wide news
259
general_news = api.get_news(limit=20, sort='desc')
260
for article in general_news:
261
print(f"{article.headline} (Symbols: {', '.join(article.symbols)})")
262
```
263
264
### Market Calendar and Clock
265
266
Access market schedule information and current market status.
267
268
```python { .api }
269
def get_clock() -> Clock:
270
"""Get current market clock information."""
271
272
def get_calendar(start: str = None, end: str = None) -> List[Calendar]:
273
"""Get market calendar information."""
274
```
275
276
**Usage Examples:**
277
278
```python
279
# Check market status
280
clock = api.get_clock()
281
print(f"Market is {'open' if clock.is_open else 'closed'}")
282
print(f"Next open: {clock.next_open}")
283
print(f"Next close: {clock.next_close}")
284
285
# Get market schedule
286
calendar = api.get_calendar('2023-01-01', '2023-01-31')
287
for day in calendar:
288
print(f"{day.date}: Open={day.open}, Close={day.close}")
289
```
290
291
## Types
292
293
```python { .api }
294
class BarV2:
295
@property
296
def symbol(self) -> str: ...
297
@property
298
def timestamp(self) -> pd.Timestamp: ...
299
@property
300
def open(self) -> float: ...
301
@property
302
def high(self) -> float: ...
303
@property
304
def low(self) -> float: ...
305
@property
306
def close(self) -> float: ...
307
@property
308
def volume(self) -> int: ...
309
@property
310
def trade_count(self) -> int: ...
311
@property
312
def vwap(self) -> float: ...
313
314
class BarsV2:
315
@property
316
def df(self) -> pd.DataFrame: ...
317
def __iter__(self): ...
318
def __len__(self) -> int: ...
319
320
class TradesV2:
321
@property
322
def df(self) -> pd.DataFrame: ...
323
def __iter__(self): ...
324
def __len__(self) -> int: ...
325
326
class QuotesV2:
327
@property
328
def df(self) -> pd.DataFrame: ...
329
def __iter__(self): ...
330
def __len__(self) -> int: ...
331
332
class NewsListV2:
333
def __iter__(self): ...
334
def __len__(self) -> int: ...
335
336
class LatestBarsV2:
337
def items(self): ...
338
def __getitem__(self, symbol: str) -> BarV2: ...
339
340
class LatestTradesV2:
341
def items(self): ...
342
def __getitem__(self, symbol: str) -> TradeV2: ...
343
344
class LatestQuotesV2:
345
def items(self): ...
346
def __getitem__(self, symbol: str) -> QuoteV2: ...
347
348
class SnapshotsV2:
349
def items(self): ...
350
def __getitem__(self, symbol: str) -> SnapshotV2: ...
351
352
class TradeV2:
353
@property
354
def symbol(self) -> str: ...
355
@property
356
def timestamp(self) -> pd.Timestamp: ...
357
@property
358
def price(self) -> float: ...
359
@property
360
def size(self) -> int: ...
361
@property
362
def exchange(self) -> str: ...
363
@property
364
def conditions(self) -> List[str]: ...
365
366
class QuoteV2:
367
@property
368
def symbol(self) -> str: ...
369
@property
370
def timestamp(self) -> pd.Timestamp: ...
371
@property
372
def bid_price(self) -> float: ...
373
@property
374
def bid_size(self) -> int: ...
375
@property
376
def ask_price(self) -> float: ...
377
@property
378
def ask_size(self) -> int: ...
379
@property
380
def bid_exchange(self) -> str: ...
381
@property
382
def ask_exchange(self) -> str: ...
383
384
class SnapshotV2:
385
@property
386
def symbol(self) -> str: ...
387
@property
388
def latest_trade(self) -> TradeV2: ...
389
@property
390
def latest_quote(self) -> QuoteV2: ...
391
@property
392
def minute_bar(self) -> BarV2: ...
393
@property
394
def daily_bar(self) -> BarV2: ...
395
@property
396
def prev_daily_bar(self) -> BarV2: ...
397
398
class NewsV2:
399
@property
400
def id(self) -> str: ...
401
@property
402
def headline(self) -> str: ...
403
@property
404
def summary(self) -> str: ...
405
@property
406
def content(self) -> str: ...
407
@property
408
def created_at(self) -> pd.Timestamp: ...
409
@property
410
def updated_at(self) -> pd.Timestamp: ...
411
@property
412
def author(self) -> str: ...
413
@property
414
def symbols(self) -> List[str]: ...
415
@property
416
def url(self) -> str: ...
417
418
class Clock:
419
@property
420
def timestamp(self) -> pd.Timestamp: ...
421
@property
422
def is_open(self) -> bool: ...
423
@property
424
def next_open(self) -> pd.Timestamp: ...
425
@property
426
def next_close(self) -> pd.Timestamp: ...
427
428
class Calendar:
429
@property
430
def date(self) -> str: ...
431
@property
432
def open(self) -> str: ...
433
@property
434
def close(self) -> str: ...
435
```