alpaca-py

repository·master·Indexed 22 days ago

https://github.com/alpacahq/alpaca-py

The official Python SDK for interacting with Alpaca's API products, including Trading, Market Data, and Broker APIs. It enables developers to build investment applications, execute algorithmic trading strategies, and stream real-time market data for stocks, crypto, and options.

Tokens
52.9K
Snippets
132
Records
352
Agent score
79%

What's inside alpaca-py

  1. Overview of Alpaca-py API capabilities

    master

    Alpaca-py provides access to three primary API suites:

    • Broker API: Used for building full brokerage experiences, including account opening, funding, and trading for end users.
    • Market Data API: Provides real-time and historical data for equities, crypto, and options.
    • Trading API: Enables trading of stocks and crypto. Paper trading is available for free to all Alpaca users.
  2. Overview of LBR Anti Setup Trading Bot

    master

    The LBR Anti Setup Trading Bot is a production-ready algorithmic trading system implementing Linda Raschke's LBR 3/10 Anti setup strategy. It targets the 'Magnificent 7' stocks (AAPL, MSFT, NVDA, GOOGL, AMZN, META, TSLA) using a serverless AWS Lambda architecture.

    Core Workflow:

    1. Trigger: Runs every weekday at 9:30 AM ET via AWS CloudWatch.
    2. Market Check: Verifies market status via Alpaca's API.
    3. Signal Scan: Filters stocks using a 6-rule technical indicator logic (MACD, ADX, EMA, ATR).
    4. Execution: Performs equal-weighted rebalancing (selling excess, buying new setups).
    5. Risk Management: Places ATR-based trailing stop orders.
    6. Persistence: Logs portfolio state to DynamoDB.
  3. Overview of the 0DTE Options Strategy Backtesting System

    master

    The 0DTE Options Strategy Backtesting System is a tool for simulating a bull put spread options strategy using zero days to expiration (0DTE) contracts. It automates the process of finding, simulating, and evaluating same-day expiry put spreads on an underlying stock (defaulting to SPY).

    Core Workflow

    1. Setup: Connect to Alpaca and Databento APIs.
    2. Data Collection: Download 1-minute interval historical stock bar data (from Alpaca) and options tick data (from Databento).
    3. Trade Simulation:
      • Scan historical data chronologically.
      • Calculate Greeks (delta) and Implied Volatility (IV) for option symbols.
      • Identify suitable option pairs (short and long legs) based on trading criteria.
      • Simulate entry, monitor for exit conditions (profit targets, stop-loss, or expiration), and manage the spread.
    4. Results: Aggregate and visualize performance metrics.

    Data Sources

    • Alpaca Trading API: Provides stock daily bars and 1-minute intraday data.
    • Databento API: Provides 1-minute options tick data including bid/ask spreads (specifically using OPRA equity options data).
  4. Manage brokerage accounts with BrokerClient

    master
    The Accounts API allows you to create brokerage accounts on behalf of your users and manage accounts under your custody. You can perform lifecycle operations such as creating, retrieving, updating, and deleting accounts, as well as managing documents and trade configurations via the alpaca.broker.client.BrokerClient class.
  5. Request different types of Crypto data

    master

    The alpaca.data.requests module provides specialized request classes to fetch various types of cryptocurrency market data. Depending on your needs, you can request historical bars, real-time quotes, individual trades, or snapshots of the current market state.

    Available request types include:

    • CryptoBarsRequest: For fetching historical OHLCV (Open, High, Low, Close, Volume) bar data.
    • CryptoQuoteRequest: For fetching historical quote data.
    • CryptoTradesRequest: For fetching historical trade data.
    • CryptoLatestQuoteRequest: For fetching the most recent quote.
    • CryptoLatestTradeRequest: For fetching the most recent trade.
    • CryptoSnapshotRequest: For fetching a comprehensive snapshot of the current market state (including latest trade, quote, and bars).
  6. LBR Signal Logic (6 Rules)

    master

    The bot identifies trading setups by filtering the Magnificent 7 stocks through six sequential technical rules:

    1. Minimum bars: Requires $\ge 31$ bars of price history.
    2. ADX filter: ADX must be $\le 32$ and not rising (rejecting strong trends).
    3. Trend filter: Price must be above the 20-bar EMA (Close > EMA(20)).
    4. Signal crossover: The MACD signal line must have crossed zero from below within the last 16 bars.
    5. Pullback: MACD must be $\le$ (signal line + $0.5 \times$ ATR).
    6. Hook: The MACD histogram must be rising.

    Symbols passing all rules are selected for equal-weight allocation.

  7. Validate data using Pydantic request models

    master

    Alpaca-py uses pydantic for runtime data validation. All request models can be instantiated by passing in data in dictionary format (e.g., from a JSON payload), allowing you to handle parsing and validation automatically.

     @app.route('/post_json', methods=['POST'])
     def do_trade():
         # ...
    
         order_data_json = request.get_json()
    
         # validate data
         MarketOrderRequest(**order_data_json)
    
         # ...
  8. Select the correct client for your API needs

    master

    Alpaca-py provides specialized client classes based on the API product and asset class you are targeting. You must instantiate the specific client required for your task:

    Broker API

    • BrokerClient

    Trading API

    • TradingClient

    Market Data API

    • StockHistoricalDataClient
    • CryptoHistoricalDataClient
    • OptionHistoricalDataClient
    • StockDataStream
    • CryptoDataStream
    • OptionDataStream
  9. Request different types of stock data

    master

    The alpaca.data.requests module provides specialized request objects used to query various types of stock market data through the Alpaca Data API. Instead of passing raw parameters to data client methods, you instantiate these request classes to define the scope of your query (e.g., specific symbols, time ranges, or frequency).

    Available request types include:

    • StockBarsRequest: For requesting historical bar/OHLCV data.
    • StockQuotesRequest: For requesting historical quote data.
    • StockTradesRequest: For requesting historical trade data.
    • StockLatestQuoteRequest: For requesting the most recent quote.
    • StockLatestTradeRequest: For requesting the most recent trade.
    • StockSnapshotRequest: For requesting a snapshot containing the latest trade, quote, and bar data.
    • MostActivesRequest: For requesting a list of the most active stocks.
    • MarketMoversRequest: For requesting market movers (gainers, losers, etc.).