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
506 changes: 143 additions & 363 deletions DEVELOPMENT_PLAN.md

Large diffs are not rendered by default.

245 changes: 221 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,26 @@ A modern Python wrapper for the Alpaca Trading API, providing easy access to tra

## ✨ Features

### Core Features
- **πŸ” Complete Alpaca API Coverage**: Trading, market data, account management, and more
- **πŸ“Š Stock Market Analysis**: Built-in screeners for gainers/losers, historical data analysis
- **πŸš€ Batch Operations**: Efficient multi-symbol data fetching with automatic batching (200+ symbols)
- **πŸ€– 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
- **🎯 Type Safety**: Full type annotations with mypy strict mode
- **πŸ§ͺ Battle-Tested**: 100+ tests with comprehensive coverage
- **⚑ Modern Python**: Async-ready, Python 3.10+ with latest best practices
- **πŸ§ͺ Battle-Tested**: 300+ tests with comprehensive coverage
- **⚑ Modern Python**: Python 3.10+ with latest best practices

### New in v3.0.0
- **πŸ“Έ Market Snapshots**: Get complete market snapshots with latest trade, quote, and bar data
- **βš™οΈ Account Configuration**: Manage PDT settings, trade confirmations, and margin configurations
- **πŸ“‹ Market Metadata**: Access condition codes, exchange information, and trading metadata
- **πŸ”„ Enhanced Orders**: Replace orders, client order IDs, and advanced order management
- **🎯 Smart Feed Management**: Automatic feed selection and fallback (SIP β†’ IEX β†’ OTC)
- **πŸ’Ύ 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

## πŸ“¦ Installation

Expand Down Expand Up @@ -306,6 +317,162 @@ sip_trades = api.stock.trades.get_trades(
)
```

### Market Snapshots

```python
# Get snapshot for a single symbol
snapshot = api.stock.snapshots.get_snapshot("AAPL")
print(f"Latest trade: ${snapshot.latest_trade.price}")
print(f"Latest quote: Bid ${snapshot.latest_quote.bid} / Ask ${snapshot.latest_quote.ask}")
print(f"Daily bar: Open ${snapshot.daily_bar.open} / Close ${snapshot.daily_bar.close}")
print(f"Previous daily: Open ${snapshot.prev_daily_bar.open} / Close ${snapshot.prev_daily_bar.close}")

# Get snapshots for multiple symbols (efficient batch operation)
symbols = ["AAPL", "GOOGL", "MSFT", "TSLA", "NVDA"]
snapshots = api.stock.snapshots.get_snapshots(symbols)
for symbol, snapshot in snapshots.items():
print(f"{symbol}: ${snapshot.latest_trade.price} ({snapshot.daily_bar.volume:,} volume)")

# Get snapshots with specific feed
snapshots = api.stock.snapshots.get_snapshots(
symbols=["SPY", "QQQ"],
feed="iex" # or "sip", "otc"
)
```

### Account Configuration

```python
# Get current account configuration
config = api.trading.account.get_configuration()
print(f"PDT Check: {config.pdt_check}")
print(f"Trade Confirm Email: {config.trade_confirm_email}")
print(f"Suspend Trade: {config.suspend_trade}")
print(f"No Shorting: {config.no_shorting}")

# Update account configuration
updated_config = api.trading.account.update_configuration(
trade_confirm_email=True,
suspend_trade=False,
pdt_check="both", # "both", "entry", or "exit"
no_shorting=False
)
print("Account configuration updated successfully")
```

### Market Metadata

```python
# Get condition codes for trades
condition_codes = api.stock.metadata.get_condition_codes(tape="A")
for code in condition_codes:
print(f"Code {code.code}: {code.description}")

# Get exchange codes
exchanges = api.stock.metadata.get_exchange_codes()
for exchange in exchanges:
print(f"{exchange.code}: {exchange.name} ({exchange.type})")

# Get all condition codes at once (cached for performance)
all_codes = api.stock.metadata.get_all_condition_codes()
print(f"Loaded {len(all_codes)} condition codes")

# Lookup specific codes
code_info = api.stock.metadata.lookup_condition_code("R")
print(f"Code R means: {code_info.description}")
```

### Enhanced Order Management

```python
# Place order with client order ID for tracking
order = api.trading.orders.market(
symbol="AAPL",
qty=1,
side="buy",
client_order_id="my-app-order-123"
)

# Replace an existing order (modify price, quantity, etc.)
replaced_order = api.trading.orders.replace_order(
order_id=order.id,
qty=2, # Change quantity
limit_price=155.00 # Add/change limit price
)

# Get order by client order ID (useful for tracking)
orders = api.trading.orders.get_all(status="open")
my_order = next((o for o in orders if o.client_order_id == "my-app-order-123"), None)

# Advanced OCO/OTO orders
oco_order = api.trading.orders.limit(
symbol="TSLA",
qty=1,
side="buy",
limit_price=200.00,
order_class="oco", # One-Cancels-Other
take_profit={"limit_price": 250.00},
stop_loss={"stop_price": 180.00}
)
```

### Smart Feed Management

```python
# The library automatically manages feed selection based on your subscription
# No configuration needed - it automatically detects and falls back as needed

# Manual feed configuration (optional)
from py_alpaca_api.http.feed_manager import FeedManager, FeedConfig, FeedType

# Configure preferred feeds
feed_config = FeedConfig(
preferred_feed=FeedType.SIP, # Try SIP first
fallback_feeds=[FeedType.IEX], # Fall back to IEX if needed
auto_fallback=True # Automatically handle permission errors
)

# The feed manager automatically:
# - Detects your subscription level (Basic/Unlimited/Business)
# - Falls back to available feeds on permission errors
# - Caches failed feeds to avoid repeated attempts
# - Provides clear logging for debugging
```

### Intelligent Caching System

```python
# Caching is built-in and automatic for improved performance
# Configure caching (optional - sensible defaults are provided)
from py_alpaca_api.cache import CacheManager, CacheConfig

# Custom cache configuration
cache_config = CacheConfig(
max_size=1000, # Maximum items in cache
default_ttl=300, # Default time-to-live in seconds
data_ttls={
"market_hours": 86400, # 1 day
"assets": 3600, # 1 hour
"quotes": 1, # 1 second
"positions": 10, # 10 seconds
}
)

# Cache manager automatically:
# - Caches frequently accessed data
# - Reduces API calls and improves response times
# - Manages memory efficiently with LRU eviction
# - Supports optional Redis backend for distributed caching

# Use the @cached decorator for custom caching
cache_manager = CacheManager(cache_config)

@cache_manager.cached("custom_data", ttl=600)
def expensive_calculation(symbol: str):
# This result will be cached for 10 minutes
return complex_analysis(symbol)
```

### Advanced Order Types

```python
Expand Down Expand Up @@ -405,27 +572,36 @@ make lint
```
py-alpaca-api/
β”œβ”€β”€ src/py_alpaca_api/
β”‚ β”œβ”€β”€ __init__.py # Main API client
β”‚ β”œβ”€β”€ exceptions.py # Custom exceptions
β”‚ β”œβ”€β”€ trading/ # Trading operations
β”‚ β”‚ β”œβ”€β”€ account.py # Account management
β”‚ β”‚ β”œβ”€β”€ orders.py # Order management
β”‚ β”‚ β”œβ”€β”€ positions.py # Position tracking
β”‚ β”‚ β”œβ”€β”€ watchlists.py # Watchlist operations
β”‚ β”‚ β”œβ”€β”€ market.py # Market data
β”‚ β”‚ β”œβ”€β”€ news.py # Financial news
β”‚ β”‚ └── recommendations.py # Stock analysis
β”‚ β”œβ”€β”€ stock/ # Stock market data
β”‚ β”‚ β”œβ”€β”€ assets.py # Asset information
β”‚ β”‚ β”œβ”€β”€ history.py # Historical data
β”‚ β”‚ β”œβ”€β”€ screener.py # Stock screening
β”‚ β”‚ β”œβ”€β”€ predictor.py # ML predictions
β”‚ β”‚ └── latest_quote.py # Real-time quotes
β”‚ β”œβ”€β”€ models/ # Data models
β”‚ └── http/ # HTTP client
β”œβ”€β”€ tests/ # Test suite
β”œβ”€β”€ docs/ # Documentation
└── pyproject.toml # Project configuration
β”‚ β”œβ”€β”€ __init__.py # Main API client
β”‚ β”œβ”€β”€ exceptions.py # Custom exceptions
β”‚ β”œβ”€β”€ trading/ # Trading operations
β”‚ β”‚ β”œβ”€β”€ account.py # Account management & configuration
β”‚ β”‚ β”œβ”€β”€ orders.py # Order management (enhanced)
β”‚ β”‚ β”œβ”€β”€ positions.py # Position tracking
β”‚ β”‚ β”œβ”€β”€ watchlists.py # Watchlist operations
β”‚ β”‚ β”œβ”€β”€ market.py # Market hours & calendar
β”‚ β”‚ β”œβ”€β”€ news.py # Financial news
β”‚ β”‚ β”œβ”€β”€ recommendations.py # Stock analysis
β”‚ β”‚ └── corporate_actions.py # Corporate events (v3.0.0)
β”‚ β”œβ”€β”€ stock/ # Stock market data
β”‚ β”‚ β”œβ”€β”€ assets.py # Asset information
β”‚ β”‚ β”œβ”€β”€ history.py # Historical data (batch support)
β”‚ β”‚ β”œβ”€β”€ screener.py # Stock screening
β”‚ β”‚ β”œβ”€β”€ predictor.py # ML predictions
β”‚ β”‚ β”œβ”€β”€ latest_quote.py # Real-time quotes (batch support)
β”‚ β”‚ β”œβ”€β”€ trades.py # Trade data API (v3.0.0)
β”‚ β”‚ β”œβ”€β”€ snapshots.py # Market snapshots (v3.0.0)
β”‚ β”‚ └── metadata.py # Market metadata (v3.0.0)
β”‚ β”œβ”€β”€ models/ # Data models
β”‚ β”œβ”€β”€ cache/ # Caching system (v3.0.0)
β”‚ β”‚ β”œβ”€β”€ cache_manager.py # Cache management
β”‚ β”‚ └── cache_config.py # Cache configuration
β”‚ └── http/ # HTTP client
β”‚ β”œβ”€β”€ requests.py # Request handling
β”‚ └── feed_manager.py # Feed management (v3.0.0)
β”œβ”€β”€ tests/ # Test suite (300+ tests)
β”œβ”€β”€ docs/ # Documentation
└── pyproject.toml # Project configuration
```

## πŸ“– Documentation
Expand Down Expand Up @@ -484,13 +660,34 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file

## πŸ—ΊοΈ Roadmap

### v3.0.0 (Current Release)
- βœ… Complete Alpaca Stock API coverage
- βœ… Market Snapshots API
- βœ… Account Configuration API
- βœ… Market Metadata API
- βœ… Enhanced Order Management
- βœ… Corporate Actions API
- βœ… Trade Data API
- βœ… Smart Feed Management System
- βœ… Intelligent Caching System
- βœ… Batch Operations for all data endpoints

### v3.1.0 (Planned)
- [ ] WebSocket support for real-time data streaming
- [ ] Live market data subscriptions
- [ ] Real-time order and trade updates

### v3.2.0 (Planned)
- [ ] Full async/await support
- [ ] Concurrent API operations
- [ ] Async context managers

### Future Releases
- [ ] Options trading support
- [ ] Crypto trading integration
- [ ] Advanced portfolio analytics
- [ ] Backtesting framework
- [ ] Strategy automation tools
- [ ] Mobile app integration

## ⚠️ Disclaimer

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "py-alpaca-api"
version = "2.2.0"
version = "3.0.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.10"
Expand Down
9 changes: 9 additions & 0 deletions src/py_alpaca_api/cache/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
"""Cache module for py-alpaca-api.

This module provides caching functionality to improve performance and reduce API calls.
"""

from .cache_config import CacheConfig, CacheType
from .cache_manager import CacheManager

__all__ = ["CacheManager", "CacheConfig", "CacheType"]
68 changes: 68 additions & 0 deletions src/py_alpaca_api/cache/cache_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
"""Cache configuration for py-alpaca-api."""

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum


class CacheType(Enum):
"""Types of cache backends supported."""

MEMORY = "memory"
REDIS = "redis"
DISABLED = "disabled"


@dataclass
class CacheConfig:
"""Configuration for cache system.

Attributes:
cache_type: Type of cache backend to use
max_size: Maximum number of items in memory cache
default_ttl: Default time-to-live in seconds
data_ttls: TTL overrides per data type
redis_host: Redis host (if using Redis)
redis_port: Redis port (if using Redis)
redis_db: Redis database number (if using Redis)
redis_password: Redis password (if using Redis)
enabled: Whether caching is enabled
"""

cache_type: CacheType = CacheType.MEMORY
max_size: int = 1000
default_ttl: int = 300 # 5 minutes default
data_ttls: dict[str, int] = field(
default_factory=lambda: {
"market_hours": 86400, # 1 day
"calendar": 86400, # 1 day
"assets": 3600, # 1 hour
"account": 60, # 1 minute
"positions": 10, # 10 seconds
"orders": 5, # 5 seconds
"quotes": 1, # 1 second
"bars": 60, # 1 minute
"trades": 60, # 1 minute
"news": 300, # 5 minutes
"watchlists": 300, # 5 minutes
"snapshots": 1, # 1 second
"metadata": 86400, # 1 day (condition codes, exchanges)
}
)
redis_host: str = "localhost"
redis_port: int = 6379
redis_db: int = 0
redis_password: str | None = None
enabled: bool = True

def get_ttl(self, data_type: str) -> int:
"""Get TTL for a specific data type.

Args:
data_type: Type of data to get TTL for

Returns:
TTL in seconds
"""
return self.data_ttls.get(data_type, self.default_ttl)
Loading
Loading