Skip to main content

Add your description here

Project description

๐Ÿš€ py-alpaca-api

Python Version PyPI Version License Tests Code Style Type Checked

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
  • ๐ŸŽฏ Type Safety: Full type annotations with mypy strict mode
  • ๐Ÿงช 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

Using pip

pip install py-alpaca-api

Using uv (recommended)

uv add py-alpaca-api

Development Installation

# Clone the repository
git clone https://github.com/TexasCoding/py-alpaca-api.git
cd py-alpaca-api

# Install with development dependencies using uv
uv sync --all-extras --dev

# Or using pip
pip install -e ".[dev]"

๐Ÿš€ Quick Start

Basic Setup

from py_alpaca_api import PyAlpacaAPI

# Initialize with your API credentials
api = PyAlpacaAPI(
    api_key="YOUR_API_KEY",
    api_secret="YOUR_SECRET_KEY",
    api_paper=True  # Use paper trading for testing
)

# Get account information
account = api.trading.account.get()
print(f"Account Balance: ${account.cash}")
print(f"Buying Power: ${account.buying_power}")

Trading Operations

# Place a market order
order = api.trading.orders.market(
    symbol="AAPL",
    qty=1,
    side="buy"
)
print(f"Order placed: {order.id}")

# Place a limit order
limit_order = api.trading.orders.limit(
    symbol="GOOGL",
    qty=1,
    side="buy",
    limit_price=150.00
)

# Get all positions
positions = api.trading.positions.get_all()
for position in positions:
    print(f"{position.symbol}: {position.qty} shares @ ${position.avg_entry_price}")

# Cancel all open orders
api.trading.orders.cancel_all()

Market Data & Analysis

# Get historical stock data for a single symbol
history = api.stock.history.get(
    symbol="TSLA",
    start="2024-01-01",
    end="2024-12-31"
)

# NEW: Get historical data for multiple symbols (batch operation)
symbols = ["AAPL", "GOOGL", "MSFT", "TSLA", "AMZN"]
multi_history = api.stock.history.get(
    symbol=symbols,  # Pass a list for batch operation
    start="2024-01-01",
    end="2024-12-31"
)
# Returns DataFrame with all symbols' data, automatically handles batching for 200+ symbols

# Get real-time quote for a single symbol
quote = api.stock.latest_quote.get("MSFT")
print(f"MSFT Price: ${quote.ask}")

# NEW: Get real-time quotes for multiple symbols (batch operation)
quotes = api.stock.latest_quote.get(["AAPL", "GOOGL", "MSFT"])
for quote in quotes:
    print(f"{quote.symbol}: ${quote.ask}")

# Screen for top gainers
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}%")

# Screen for top losers
losers = api.stock.screener.losers(
    price_greater_than=10.0,
    change_less_than=-5.0,
    volume_greater_than=1000000
)

Stock Predictions with ML

# Predict future stock prices using Prophet
predictions = api.stock.predictor.predict(
    symbol="AAPL",
    days_to_predict=30,
    forecast_days_back=365
)

# Get prediction for specific date
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

# Get latest financial news
news = api.trading.news.get(symbol="NVDA")
for article in news[:5]:
    print(f"- {article['headline']}")
    print(f"  Sentiment: {article.get('sentiment', 'N/A')}")

# Get stock recommendations
recommendations = api.trading.recommendations.get_recommendations("META")
sentiment = api.trading.recommendations.get_sentiment("META")
print(f"META Sentiment: {sentiment}")

Portfolio Analysis

# Get portfolio history
portfolio_history = api.trading.account.portfolio_history(
    period="1M",
    timeframe="1D"
)

# Calculate returns
returns = (
    (portfolio_history['equity'].iloc[-1] - portfolio_history['equity'].iloc[0]) /
    portfolio_history['equity'].iloc[0] * 100
)
print(f"Monthly Return: {returns:.2f}%")

# Get account activities
activities = api.trading.account.get_activities()
for activity in activities:
    print(f"{activity.created_at}: {activity.activity_type} - {activity.symbol}")

๐Ÿ“Š Advanced Features

Watchlist Management

# Create a watchlist
watchlist = api.trading.watchlists.create_watchlist(
    name="Tech Stocks",
    symbols=["AAPL", "GOOGL", "MSFT", "NVDA"]
)

# Add symbols to existing watchlist
api.trading.watchlists.add_assets_to_watchlist(
    watchlist_id=watchlist.id,
    symbols=["META", "AMZN"]
)

# Get all watchlists
watchlists = api.trading.watchlists.get_all_watchlists()

Corporate Actions

# Get dividend announcements
dividends = api.trading.corporate_actions.get_announcements(
    since="2024-01-01",
    until="2024-03-31",
    ca_types=["dividend"],
    symbol="AAPL"  # Optional: filter by symbol
)

for dividend in dividends:
    print(f"{dividend.initiating_symbol}: ${dividend.cash_amount} on {dividend.payable_date}")

# Get stock splits
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")

# Get mergers and acquisitions
mergers = api.trading.corporate_actions.get_announcements(
    since="2024-01-01",
    until="2024-03-31",
    ca_types=["merger"]
)

# Get specific announcement by ID
announcement = api.trading.corporate_actions.get_announcement_by_id("123456")
print(f"Corporate Action: {announcement.ca_type} for {announcement.initiating_symbol}")

# Get all types of corporate actions
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"  # Filter by specific date type
)

Trade Data

# Get historical trades for a symbol
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}")

# Get latest trade for a symbol
latest_trade = api.stock.trades.get_latest_trade("MSFT")
print(f"Latest MSFT trade: ${latest_trade.price} x {latest_trade.size}")

# Get trades for multiple symbols
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")

# Get all trades with automatic pagination
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)}")

# Use different data feeds (requires subscription)
sip_trades = api.stock.trades.get_trades(
    symbol="AAPL",
    start="2024-01-15T09:30:00Z",
    end="2024-01-15T10:00:00Z",
    feed="sip"  # or "iex", "otc"
)

Market Snapshots

# 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

# 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

# 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

# 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

# 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

# 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

# Stop-loss order
stop_loss = api.trading.orders.stop(
    symbol="TSLA",
    qty=1,
    side="sell",
    stop_price=180.00
)

# Trailing stop order
trailing_stop = api.trading.orders.trailing_stop(
    symbol="NVDA",
    qty=1,
    side="sell",
    trail_percent=5.0  # 5% trailing stop
)

# One-Cancels-Other (OCO) order
oco_order = api.trading.orders.market(
    symbol="AAPL",
    qty=1,
    side="buy",
    take_profit=200.00,
    stop_loss=150.00
)

Market Hours & Calendar

# Check if market is open
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}")

# Get market calendar
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:

# Run all tests
./test.sh

# Run specific test file
./test.sh tests/test_trading/test_orders.py

# Run with coverage
uv run pytest --cov=py_alpaca_api --cov-report=html

# Run with markers
uv run pytest -m "not slow"  # Skip slow tests

๐Ÿ› ๏ธ Development

Setup Development Environment

# Install development dependencies
uv sync --all-extras --dev

# Install pre-commit hooks
pre-commit install

# Run code quality checks
make check

# Format code
make format

# Run type checking
make type-check

# Run linting
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)
โ”‚   โ”‚   โ”œโ”€โ”€ 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.

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. 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

Tests Python Version Last Commit Issues

๐Ÿ—บ๏ธ 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

โš ๏ธ 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

GitHub Stars

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

py_alpaca_api-3.0.0.tar.gz (222.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

py_alpaca_api-3.0.0-py3-none-any.whl (66.3 kB view details)

Uploaded Python 3

File details

Details for the file py_alpaca_api-3.0.0.tar.gz.

File metadata

  • Download URL: py_alpaca_api-3.0.0.tar.gz
  • Upload date:
  • Size: 222.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.6.14

File hashes

Hashes for py_alpaca_api-3.0.0.tar.gz
Algorithm Hash digest
SHA256 308184c5037954008e5ee0b9442ab7dbef2e496a395bf08851d00272d58336e7
MD5 6a4d8bfabf02cfe5d1af65166fe3bef7
BLAKE2b-256 107a2d8cda6899fdf428873d7bf43a2ca378361fbd5403bf6ea643d43536dd4e

See more details on using hashes here.

File details

Details for the file py_alpaca_api-3.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for py_alpaca_api-3.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 3db1dddacb30b2d1c177d9f26b063dc696fb7752579189ef0b6c2480bcd03c2a
MD5 6ffade72bb932a721725d66243977fc4
BLAKE2b-256 96d909198867f5147bcd30cf2f2babe69906c839ee8bce608b87e450ca0faf7f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page