Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,37 @@ All notable changes to py-alpaca-api will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [3.0.1] - 2025-09-20

### Overview
Complete implementation of all Alpaca Market Data API endpoints, achieving 100% API coverage for both Trading and Market Data APIs.

### Added
- ✅ **Complete Market Data API Coverage** - All 11 endpoints now implemented
- Historical Quotes API (`quotes.get_historical_quotes()`) - Bid/ask quotes with spread calculations
- Historical Auctions API (`auctions.get_auctions()`, `auctions.get_daily_auctions()`) - Opening and closing auction data
- Company Logos API (`logos.get_logo()`, `logos.save_logo()`, `logos.get_logo_url()`) - Company logo retrieval
- Latest Bars API (`history.get_latest_bars()`) - Get the most recent bar for symbols
- ✅ **Complete Trading API Coverage** - All 28 endpoints fully implemented
- `get_all_orders()` method for comprehensive order retrieval with filtering
- 📚 **Enhanced Documentation**
- Complete documentation for all new modules
- Code examples for quotes, auctions, and logos
- Updated README with all new features
- 🧪 **Comprehensive Testing** - 350+ tests with full coverage
- 18 tests for logos functionality
- 11 tests for historical quotes
- 14 tests for historical auctions
- 8 tests for latest bars

### Changed
- Extended `Requests` class to support raw binary responses for logo retrieval
- Updated documentation structure to include all new modules

### Fixed
- Type checking issues in auctions module with DataFrame aggregation
- Control flow in logos module for better error handling

## [3.0.0] - Unreleased

### Overview
Expand Down
106 changes: 106 additions & 0 deletions MARKET_DATA_API_AUDIT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
# Alpaca Market Data API Implementation Audit

## 📊 Stock Market Data API Endpoints

### Current Implementation Status

| Endpoint | Path | Status | Implementation |
|----------|------|--------|----------------|
| **Historical Bars** | GET `/v2/stocks/bars` | ✅ Implemented | `history.get_stock_data()`, `history.get_historical_data()` |
| **Latest Bars** | GET `/v2/stocks/bars/latest` | ✅ Implemented | `history.get_latest_bars()` |
| **Historical Trades** | GET `/v2/stocks/trades` | ✅ Implemented | `trades.get_trades()`, `trades.get_trades_multi()` |
| **Latest Trades** | GET `/v2/stocks/trades/latest` | ✅ Implemented | `trades.get_latest_trade()`, `trades.get_latest_trades_multi()` |
| **Historical Quotes** | GET `/v2/stocks/quotes` | ✅ Implemented | `quotes.get_historical_quotes()` |
| **Latest Quotes** | GET `/v2/stocks/quotes/latest` | ✅ Implemented | `latest_quote.get()` |
| **Snapshots** | GET `/v2/stocks/{symbol}/snapshot` | ✅ Implemented | `snapshots.get_snapshot()`, `snapshots.get_snapshots()` |
| **Historical Auctions** | GET `/v2/stocks/auctions` | ✅ Implemented | `auctions.get_auctions()`, `auctions.get_daily_auctions()` |
| **Company Logos** | GET `/v1beta1/logos/{symbol}` | ✅ Implemented | `logos.get_logo()`, `logos.get_logo_url()`, `logos.save_logo()` |
| **Exchange Codes** | GET `/v2/stocks/meta/exchanges` | ✅ Implemented | `metadata.get_exchange_codes()` |
| **Condition Codes** | GET `/v2/stocks/meta/conditions` | ✅ Implemented | `metadata.get_condition_codes()` |

## ✅ UPDATE: All Endpoints Now Implemented!

As of this latest update, **ALL** market data endpoints have been implemented:
- ✅ **Latest Bars** - Added `history.get_latest_bars()` method
- ✅ **Historical Quotes** - Added complete `quotes.py` module with `get_historical_quotes()`
- ✅ **Historical Auctions** - Added complete `auctions.py` module with `get_auctions()` and `get_daily_auctions()`
- ✅ **Company Logos** - Added complete `logos.py` module with multiple retrieval methods

## ✅ Implemented Features

### 1. Historical Bars (Complete)
- ✅ `history.get_stock_data()` - Gets historical bars with various timeframes
- ✅ `history.get_historical_data()` - Wrapper for stock data retrieval
- ✅ `history.get_latest_bars()` - Gets latest bars for symbols
- ✅ Batch processing for multiple symbols

### 2. Trades
- ✅ `trades.get_trades()` - Get historical trades for a symbol
- ✅ `trades.get_latest_trade()` - Get latest trade for a symbol
- ✅ `trades.get_trades_multi()` - Get trades for multiple symbols
- ✅ `trades.get_latest_trades_multi()` - Get latest trades for multiple symbols
- ✅ `trades.get_all_trades()` - Get all trades with pagination

### 3. Quotes (Complete)
- ✅ `quotes.get_historical_quotes()` - Get historical quotes with bid/ask data
- ✅ `latest_quote.get()` - Get latest quotes
- ✅ Batch processing for multiple symbols
- ✅ Spread calculation and analysis

### 4. Snapshots
- ✅ `snapshots.get_snapshot()` - Get snapshot for single symbol
- ✅ `snapshots.get_snapshots()` - Get snapshots for multiple symbols
- ✅ Includes latest trade, quote, bars data

### 5. Auctions (Complete)
- ✅ `auctions.get_auctions()` - Get historical auction data
- ✅ `auctions.get_daily_auctions()` - Get daily aggregated auction summaries
- ✅ Support for opening and closing auction prices
- ✅ Intraday return calculations

### 6. Company Logos (Complete)
- ✅ `logos.get_logo()` - Get logo as binary image data
- ✅ `logos.get_logo_url()` - Get direct URL to logo
- ✅ `logos.save_logo()` - Save logo to file
- ✅ `logos.get_logo_base64()` - Get logo as base64 string
- ✅ `logos.get_multiple_logos()` - Batch retrieval for multiple symbols
- ✅ Support for placeholder images

### 7. Metadata
- ✅ `metadata.get_exchange_codes()` - Get exchange code mappings
- ✅ `metadata.get_condition_codes()` - Get condition code mappings
- ✅ `metadata.lookup_exchange()` - Look up exchange by code
- ✅ `metadata.lookup_condition()` - Look up condition by code
- ✅ Caching support for metadata

### 8. Additional Features (Not in standard API)
- ✅ `assets.get()` - Get asset information
- ✅ `assets.get_all()` - Get all assets
- ✅ `screener.gainers()` - Find top gaining stocks
- ✅ `screener.losers()` - Find top losing stocks
- ✅ `predictor.get_losers_to_gainers()` - ML-based predictions

## 📊 Summary

- **Total Market Data Endpoints**: 11
- **Implemented**: 11 (100%)
- **Missing**: 0 (0%)

## 🎉 Complete Implementation Achieved!

All Alpaca Market Data API endpoints for stocks are now fully implemented. The library provides:
- Complete historical and real-time data access
- Full support for bars, trades, quotes, auctions, and snapshots
- Metadata endpoints for exchange and condition codes
- Additional analysis tools (screeners, predictors)
- Batch processing and pagination support
- Type-safe implementations with full mypy compliance

## 📝 Implementation Notes

- All endpoints support feed selection (IEX/SIP/OTC)
- Pagination is implemented for large data sets
- Batch processing is available for multi-symbol requests
- Type annotations and mypy compliance throughout
- Proper error handling with custom exceptions
- Consistent DataFrame output for data analysis
58 changes: 57 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,11 @@ A modern Python wrapper for the Alpaca Trading API, providing easy access to tra
- **🤖 ML-Powered Predictions**: Stock price predictions using Facebook Prophet
- **📰 Financial News Integration**: Real-time news from Yahoo Finance and Benzinga
- **📈 Technical Analysis**: Stock recommendations and sentiment analysis
- **📉 Bid/Ask Quotes**: Historical quote data with spread analysis
- **🔔 Auction Data**: Opening and closing auction prices and volumes
- **🖼️ Company Logos**: Retrieve company logos for display
- **🎯 Type Safety**: Full type annotations with mypy strict mode
- **🧪 Battle-Tested**: 300+ tests with comprehensive coverage
- **🧪 Battle-Tested**: 350+ tests with comprehensive coverage
- **⚡ Modern Python**: Python 3.10+ with latest best practices

### New in v3.0.0
Expand All @@ -31,6 +34,9 @@ A modern Python wrapper for the Alpaca Trading API, providing easy access to tra
- **💾 Intelligent Caching**: Built-in caching system with configurable TTLs for optimal performance
- **🏢 Corporate Actions**: Track dividends, splits, mergers, and other corporate events
- **📊 Trade Data API**: Access historical and real-time trade data with pagination
- **📉 Historical Quotes API**: Bid/ask quotes with spread calculations
- **🔔 Auction Data API**: Opening and closing auction prices and volumes
- **🖼️ Company Logos API**: Retrieve company logo images

## 📦 Installation

Expand Down Expand Up @@ -206,6 +212,53 @@ for activity in activities:
print(f"{activity.created_at}: {activity.activity_type} - {activity.symbol}")
```

### Market Data - Quotes, Auctions & Logos

```python
# Get historical quotes with bid/ask spreads
quotes = api.stock.quotes.get_historical_quotes(
"AAPL",
start="2024-01-01T09:30:00Z",
end="2024-01-01T16:00:00Z"
)
print(f"Average spread: ${quotes['spread'].mean():.4f}")
print(f"Spread percentage: {quotes['spread_pct'].mean():.4f}%")

# Get auction data (opening and closing auctions)
auctions = api.stock.auctions.get_auctions(
["AAPL", "MSFT"],
start="2024-01-01",
end="2024-01-31"
)
for symbol, df in auctions.items():
print(f"{symbol} average intraday return: {df['intraday_return'].mean():.2f}%")

# Get daily aggregated auction data
daily_auctions = api.stock.auctions.get_daily_auctions(
"AAPL",
start="2024-01-01",
end="2024-01-31"
)
print(f"Days with positive returns: {len(daily_auctions[daily_auctions['daily_return'] > 0])}")

# Get company logos
logo_url = api.stock.logos.get_logo_url("AAPL")
print(f"Apple logo URL: {logo_url}")

# Save logo to file
api.stock.logos.save_logo("MSFT", "msft_logo.png")

# Get logo as base64 for embedding
logo_base64 = api.stock.logos.get_logo_base64("GOOGL")
html = f'<img src="data:image/png;base64,{logo_base64}" alt="Google logo">'

# Get logos for multiple companies
logos = api.stock.logos.get_multiple_logos(
["AAPL", "MSFT", "GOOGL"],
placeholder=True # Use placeholder if logo not found
)
```

## 📊 Advanced Features

### Watchlist Management
Expand Down Expand Up @@ -586,6 +639,9 @@ py-alpaca-api/
│ ├── stock/ # Stock market data
│ │ ├── assets.py # Asset information
│ │ ├── history.py # Historical data (batch support)
│ │ ├── quotes.py # Historical quotes with bid/ask (v3.0.0)
│ │ ├── auctions.py # Opening/closing auctions (v3.0.0)
│ │ ├── logos.py # Company logos (v3.0.0)
│ │ ├── screener.py # Stock screening
│ │ ├── predictor.py # ML predictions
│ │ ├── latest_quote.py # Real-time quotes (batch support)
Expand Down
88 changes: 88 additions & 0 deletions TRADING_API_AUDIT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# Alpaca Trading API Implementation Audit

## ✅ Implemented Endpoints

### Account
- ✅ GET /v2/account - `account.get()`
- ✅ GET /account/configurations - `account.get_configuration()`
- ✅ PATCH /account/configurations - `account.update_configuration()`
- ✅ GET /account/activities - `account.activities()`
- ✅ GET /account/activities/{type} - `account.activities(activity_type=...)`
- ✅ GET /account/portfolio/history - `account.portfolio_history()`

### Orders
- ✅ POST /orders - Multiple methods:
- `orders.market()`
- `orders.limit()`
- `orders.stop()`
- `orders.stop_limit()`
- `orders.trailing_stop()`
- `orders._submit_order()` (internal)
- ✅ GET /orders - `orders.get_all_orders()` (just implemented!)
- ✅ DELETE /orders - `orders.cancel_all()`
- ✅ GET /orders/by_client_order_id - `orders.get_by_client_order_id()`
- ✅ GET /orders/{order_id} - `orders.get_by_id()`
- ✅ PATCH /orders/{order_id} - `orders.replace_order()`
- ✅ DELETE /orders/{order_id} - `orders.cancel_by_id()`

### Positions
- ✅ GET /positions - `positions.get_all()`
- ✅ DELETE /positions - `positions.close_all()`
- ✅ GET /positions/{symbol_or_asset_id} - `positions.get()`
- ✅ DELETE /positions/{symbol_or_asset_id} - `positions.close()`
- ✅ POST /positions/{symbol_or_asset_id}/exercise - `positions.exercise()` (implemented!)

### Watchlists
- ✅ GET /watchlists - `watchlists.get_all()`
- ✅ POST /watchlists - `watchlists.create()`
- ✅ GET /watchlists/{watchlist_id} - `watchlists.get()`
- ✅ PUT /watchlists/{watchlist_id} - `watchlists.update()`
- ✅ DELETE /watchlists/{watchlist_id} - `watchlists.delete()`
- ✅ POST /watchlists/{watchlist_id}/assets - `watchlists.add_asset()`
- ✅ DELETE /watchlists/{watchlist_id}/{symbol} - `watchlists.remove_asset()` (implemented)

### Market/Calendar
- ✅ GET /calendar - `market.calendar()`
- ✅ GET /clock - `market.clock()`

### Corporate Actions (Announcements)
- ✅ GET /corporate_actions/announcements - `corporate_actions.get_announcements()`
- ✅ GET /corporate_actions/announcements/{id} - `corporate_actions.get_announcement_by_id()`

### Additional Features (Not in standard API)
- ✅ News aggregation - `news.get_news()`
- ✅ Stock recommendations/sentiment - `recommendations.get_recommendations()`, `recommendations.get_sentiment()`

## ✅ Complete Implementation

All Alpaca Trading API endpoints are now fully implemented!

## 📋 Summary

- **Total API Endpoints**: 28
- **Implemented**: 28 (100%)
- **Missing**: 0 (0%)

## 🎉 Recent Additions

1. **GET /orders** - `orders.get_all_orders()`
- Retrieves a list of orders with filtering options
- Supports status, symbols, limit, date range, and sorting parameters

2. **POST /positions/{symbol_or_asset_id}/exercise** - `positions.exercise()`
- Exercise options positions
- Processes exercise requests immediately
- Returns confirmation of exercise submission

## ✨ All Trading Features Available

The py-alpaca-api library now provides complete coverage of the Alpaca Trading API, including:
- Account management and configuration
- Order placement, retrieval, and management (all order types)
- Position tracking and management (including options exercise)
- Watchlist CRUD operations
- Market calendar and clock information
- Corporate actions/announcements
- Portfolio history
- Account activities
- Additional features like news aggregation and sentiment analysis
6 changes: 4 additions & 2 deletions docs/source/api/py_alpaca_api/http/requests/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ Module Contents
.. py:attribute:: session


.. py:method:: request(method: str, url: str, headers: dict[str, str] | None = None, params: dict[str, str | bool | float | int] | None = None, json: dict[str, Any] | None = None)
.. py:method:: request(method: str, url: str, headers: dict[str, str] | None = None, params: dict[str, str | bool | float | int] | None = None, json: dict[str, Any] | None = None, raw_response: bool = False)

Execute HTTP request with retry logic.

Expand All @@ -36,8 +36,10 @@ Module Contents
:param params: An optional dictionary containing the query parameters for the
request.
:param json: An optional dictionary containing the JSON payload for the request.
:param raw_response: If True, return the raw response object without status checks.
Defaults to False.

:returns: The response object returned by the server.

:raises APIRequestError: If the response status code is not one of the
acceptable statuses (200, 204, 207).
acceptable statuses (200, 204, 207) and raw_response is False.
Loading
Loading