🚀 py-alpaca-api

A modern Python wrapper for the Alpaca Trading API, providing easy access to trading, market data, and account management functionality with full type safety and comprehensive testing.
✨ 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
- 📉 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: 350+ 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
- 📉 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
Using pip
pip install py-alpaca-api
Using uv (recommended)
uv add py-alpaca-api
Development Installation
git clone https://github.com/TexasCoding/py-alpaca-api.git
cd py-alpaca-api
uv sync --all-extras --dev
pip install -e ".[dev]"
🚀 Quick Start
Basic Setup
from py_alpaca_api import PyAlpacaAPI
api = PyAlpacaAPI(
api_key="YOUR_API_KEY",
api_secret="YOUR_SECRET_KEY",
api_paper=True
)
account = api.trading.account.get()
print(f"Account Balance: ${account.cash}")
print(f"Buying Power: ${account.buying_power}")
Trading Operations
order = api.trading.orders.market(
symbol="AAPL",
qty=1,
side="buy"
)
print(f"Order placed: {order.id}")
limit_order = api.trading.orders.limit(
symbol="GOOGL",
qty=1,
side="buy",
limit_price=150.00
)
positions = api.trading.positions.get_all()
for position in positions:
print(f"{position.symbol}: {position.qty} shares @ ${position.avg_entry_price}")
api.trading.orders.cancel_all()
Market Data & Analysis
history = api.stock.history.get(
symbol="TSLA",
start="2024-01-01",
end="2024-12-31"
)
symbols = ["AAPL", "GOOGL", "MSFT", "TSLA", "AMZN"]
multi_history = api.stock.history.get(
symbol=symbols,
start="2024-01-01",
end="2024-12-31"
)
quote = api.stock.latest_quote.get("MSFT")
print(f"MSFT Price: ${quote.ask}")
quotes = api.stock.latest_quote.get(["AAPL", "GOOGL", "MSFT"])
for quote in quotes:
print(f"{quote.symbol}: ${quote.ask}")
gainers = api.stock.screener.gainers(
price_greater_than=10.0,
change_greater_than=5.0,
volume_greater_than=1000000
)
print("Top Gainers:")
for stock in gainers.head(10).itertuples():
print(f"{stock.symbol}: +{stock.change}%")
losers = api.stock.screener.losers(
price_greater_than=10.0,
change_less_than=-5.0,
volume_greater_than=1000000
)
Stock Predictions with ML
predictions = api.stock.predictor.predict(
symbol="AAPL",
days_to_predict=30,
forecast_days_back=365
)
future_price = predictions[predictions['ds'] == '2024-12-31']['yhat'].values[0]
print(f"Predicted AAPL price on 2024-12-31: ${future_price:.2f}")
Financial News & Sentiment
news = api.trading.news.get(symbol="NVDA")
for article in news[:5]:
print(f"- {article['headline']}")
print(f" Sentiment: {article.get('sentiment', 'N/A')}")
recommendations = api.trading.recommendations.get_recommendations("META")
sentiment = api.trading.recommendations.get_sentiment("META")
print(f"META Sentiment: {sentiment}")
Portfolio Analysis
portfolio_history = api.trading.account.portfolio_history(
period="1M",
timeframe="1D"
)
returns = (
(portfolio_history['equity'].iloc[-1] - portfolio_history['equity'].iloc[0]) /
portfolio_history['equity'].iloc[0] * 100
)
print(f"Monthly Return: {returns:.2f}%")
activities = api.trading.account.get_activities()
for activity in activities:
print(f"{activity.created_at}: {activity.activity_type} - {activity.symbol}")
Market Data - Quotes, Auctions & Logos
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}%")
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}%")
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])}")
logo_url = api.stock.logos.get_logo_url("AAPL")
print(f"Apple logo URL: {logo_url}")
api.stock.logos.save_logo("MSFT", "msft_logo.png")
logo_base64 = api.stock.logos.get_logo_base64("GOOGL")
html = f'<img src="data:image/png;base64,{logo_base64}" alt="Google logo">'
logos = api.stock.logos.get_multiple_logos(
["AAPL", "MSFT", "GOOGL"],
placeholder=True
)
📊 Advanced Features
Watchlist Management
watchlist = api.trading.watchlists.create_watchlist(
name="Tech Stocks",
symbols=["AAPL", "GOOGL", "MSFT", "NVDA"]
)
api.trading.watchlists.add_assets_to_watchlist(
watchlist_id=watchlist.id,
symbols=["META", "AMZN"]
)
watchlists = api.trading.watchlists.get_all_watchlists()
Corporate Actions
dividends = api.trading.corporate_actions.get_announcements(
since="2024-01-01",
until="2024-03-31",
ca_types=["dividend"],
symbol="AAPL"
)
for dividend in dividends:
print(f"{dividend.initiating_symbol}: ${dividend.cash_amount} on {dividend.payable_date}")
splits = api.trading.corporate_actions.get_announcements(
since="2024-01-01",
until="2024-03-31",
ca_types=["split"]
)
for split in splits:
print(f"{split.initiating_symbol}: {split.split_from}:{split.split_to} split")
mergers = api.trading.corporate_actions.get_announcements(
since="2024-01-01",
until="2024-03-31",
ca_types=["merger"]
)
announcement = api.trading.corporate_actions.get_announcement_by_id("123456")
print(f"Corporate Action: {announcement.ca_type} for {announcement.initiating_symbol}")
all_actions = api.trading.corporate_actions.get_announcements(
since="2024-01-01",
until="2024-03-31",
ca_types=["dividend", "split", "merger", "spinoff"],
date_type="ex_dividend"
)
Trade Data
trades_response = api.stock.trades.get_trades(
symbol="AAPL",
start="2024-01-15T09:30:00Z",
end="2024-01-15T10:00:00Z",
limit=100
)
for trade in trades_response.trades:
print(f"Trade: {trade.size} shares @ ${trade.price} on {trade.exchange}")
latest_trade = api.stock.trades.get_latest_trade("MSFT")
print(f"Latest MSFT trade: ${latest_trade.price} x {latest_trade.size}")
multi_trades = api.stock.trades.get_trades_multi(
symbols=["AAPL", "MSFT", "GOOGL"],
start="2024-01-15T09:30:00Z",
end="2024-01-15T10:00:00Z",
limit=10
)
for symbol, trades_data in multi_trades.items():
print(f"{symbol}: {len(trades_data.trades)} trades")
all_trades = api.stock.trades.get_all_trades(
symbol="SPY",
start="2024-01-15T09:30:00Z",
end="2024-01-15T09:35:00Z"
)
print(f"Total SPY trades: {len(all_trades)}")
sip_trades = api.stock.trades.get_trades(
symbol="AAPL",
start="2024-01-15T09:30:00Z",
end="2024-01-15T10:00:00Z",
feed="sip"
)
Market Snapshots
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}")
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)")
snapshots = api.stock.snapshots.get_snapshots(
symbols=["SPY", "QQQ"],
feed="iex"
)
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}")
updated_config = api.trading.account.update_configuration(
trade_confirm_email=True,
suspend_trade=False,
pdt_check="both",
no_shorting=False
)
print("Account configuration updated successfully")
Market Metadata
condition_codes = api.stock.metadata.get_condition_codes(tape="A")
for code in condition_codes:
print(f"Code {code.code}: {code.description}")
exchanges = api.stock.metadata.get_exchange_codes()
for exchange in exchanges:
print(f"{exchange.code}: {exchange.name} ({exchange.type})")
all_codes = api.stock.metadata.get_all_condition_codes()
print(f"Loaded {len(all_codes)} condition codes")
code_info = api.stock.metadata.lookup_condition_code("R")
print(f"Code R means: {code_info.description}")
Enhanced Order Management
order = api.trading.orders.market(
symbol="AAPL",
qty=1,
side="buy",
client_order_id="my-app-order-123"
)
replaced_order = api.trading.orders.replace_order(
order_id=order.id,
qty=2,
limit_price=155.00
)
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)
oco_order = api.trading.orders.limit(
symbol="TSLA",
qty=1,
side="buy",
limit_price=200.00,
order_class="oco",
take_profit={"limit_price": 250.00},
stop_loss={"stop_price": 180.00}
)
Smart Feed Management
from py_alpaca_api.http.feed_manager import FeedManager, FeedConfig, FeedType
feed_config = FeedConfig(
preferred_feed=FeedType.SIP,
fallback_feeds=[FeedType.IEX],
auto_fallback=True
)
Intelligent Caching System
from py_alpaca_api.cache import CacheManager, CacheConfig
cache_config = CacheConfig(
max_size=1000,
default_ttl=300,
data_ttls={
"market_hours": 86400,
"assets": 3600,
"quotes": 1,
"positions": 10,
}
)
cache_manager = CacheManager(cache_config)
@cache_manager.cached("custom_data", ttl=600)
def expensive_calculation(symbol: str):
return complex_analysis(symbol)
Advanced Order Types
stop_loss = api.trading.orders.stop(
symbol="TSLA",
qty=1,
side="sell",
stop_price=180.00
)
trailing_stop = api.trading.orders.trailing_stop(
symbol="NVDA",
qty=1,
side="sell",
trail_percent=5.0
)
oco_order = api.trading.orders.market(
symbol="AAPL",
qty=1,
side="buy",
take_profit=200.00,
stop_loss=150.00
)
Market Hours & Calendar
clock = api.trading.market.clock()
print(f"Market is {'open' if clock.is_open else 'closed'}")
print(f"Next open: {clock.next_open}")
print(f"Next close: {clock.next_close}")
calendar = api.trading.market.calendar(
start_date="2024-01-01",
end_date="2024-12-31"
)
🧪 Testing
The project includes comprehensive test coverage. Run tests using:
./test.sh
./test.sh tests/test_trading/test_orders.py
uv run pytest --cov=py_alpaca_api --cov-report=html
uv run pytest -m "not slow"
🛠️ Development
Setup Development Environment
uv sync --all-extras --dev
pre-commit install
make check
make format
make type-check
make lint
Code Quality Tools
- Ruff: Fast Python linter and formatter
- MyPy: Static type checker with strict mode
- Pre-commit: Git hooks for code quality
- Pytest: Testing framework with coverage
Project Structure
py-alpaca-api/
├── src/py_alpaca_api/
│ ├── __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)
│ │ ├── 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)
│ │ ├── 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
Full documentation is available at Read the Docs
API Reference
🤝 Contributing
We welcome contributions! Please see our Contributing Guidelines for details.
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
)
- Commit your changes (
git commit -m 'Add amazing feature'
)
- Push to the branch (
git push origin feature/amazing-feature
)
- Open a Pull Request
Development Guidelines
- Write tests for new features
- Follow the existing code style (enforced by ruff)
- Add type hints to all functions
- Update documentation as needed
- Ensure all tests pass before submitting PR
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
📞 Support
🚦 Project Status

🗺️ 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)
v3.2.0 (Planned)
Future Releases
⚠️ Disclaimer
This software is for educational purposes only. Do not risk money which you are afraid to lose. USE THE SOFTWARE AT YOUR OWN RISK. THE AUTHORS AND ALL AFFILIATES ASSUME NO RESPONSIBILITY FOR YOUR TRADING RESULTS.
Always start with paper trading to test your strategies before using real money.
Made with ❤️ by the py-alpaca-api team