Skip to main content

Alpaca-py

Downloads Python Versions GitHub PyPI

Table of Contents

About

Alpaca-py provides an interface for interacting with the API products Alpaca offers. These API products are provided as various REST, WebSocket and SSE endpoints that allow you to do everything from streaming market data to creating your own investment apps.

Learn more about the API products Alpaca offers at https://alpaca.markets.

Documentation

Alpaca-py has a supplementary documentation site which contains references for all clients, methods and models found in this codebase. The documentation also contains examples to get started with alpaca-py.

You can find the documentation site here: https://alpaca.markets/sdks/python/getting_started.html

You can also find the API Reference of Alpaca APIs: https://docs.alpaca.markets/reference

Installation

Alpaca-py is supported on Python 3.10+. You can install Alpaca-py using pip.

Run the following command in your terminal.

  pip install alpaca-py

Update

If you already have Alpaca-py installed, and would like to use the latest version available...

Run the following command in your terminal:

  pip install alpaca-py --upgrade

What’s New?

If you’ve used the previous python SDK alpaca-trade-api, there are a few key differences to be aware of.

Broker API

Alpaca-py lets you use Broker API to start building your investment apps! Learn more at the Broker page.

OOP Design

Alpaca-py uses a more OOP approach to submitting requests compared to the previous SDK. To submit a request, you will most likely need to create a request object containing the desired request data. Generally, there is a unique request model for each method.

Some examples of request models corresponding to methods:

  • GetOrdersRequest for TradingClient.get_orders()
  • CryptoLatestOrderbookRequest for CryptoHistoricalDataClient.get_crypto_latest_orderbook()

Request Models Usage Example

To get historical bar data for crypto, you will need to provide a CryptoBarsRequest object.

from alpaca.data.historical import CryptoHistoricalDataClient
from alpaca.data.requests import CryptoBarsRequest
from alpaca.data.timeframe import TimeFrame
from datetime import datetime

# no keys required for crypto data
client = CryptoHistoricalDataClient()

request_params = CryptoBarsRequest(
                        symbol_or_symbols=["BTC/USD", "ETH/USD"],
                        timeframe=TimeFrame.Day,
                        start=datetime(2022, 7, 1)
                 )

bars = client.get_crypto_bars(request_params)

Data Validation

Alpaca-py uses pydantic to validate data models at run-time. This means if you are receiving request data via JSON from a client. You can handle parsing and validation through Alpaca’s request models. All request models can be instantiated by passing in data in dictionary format.

Here is a rough example of what is possible.

 @app.route('/post_json', methods=['POST'])
 def do_trade():
     # ...

     order_data_json = request.get_json()

     # validate data
     MarketOrderRequest(**order_data_json)

     # ...

Many Clients

Alpaca-py has a lot of client classes. There is a client for each API and even asset class specific clients (StockHistoricalDataClient, CryptoDataStream, OptionHistoricalDataClient). This requires you to pick and choose clients based on your needs.

Broker API: BrokerClient

Trading API: TradingClient

Market Data API: StockHistoricalDataClient, CryptoHistoricalDataClient, NewsClient, OptionHistoricalDataClient, CryptoDataStream, StockDataStream, NewsDataStream, OptionDataStream

API Keys

Trading and Market Data API

In order to use Alpaca’s services you’ll need to sign up for an Alpaca account and retrieve your API keys. Signing up is completely free and takes only a few minutes. Sandbox environments are available to test out the API. To use the sandbox environment, you will need to provide sandbox/paper keys. API keys are passed into Alpaca-py through either TradingClient, StockHistoricalDataClient, CryptoHistoricalDataClient, NewsClient, OptionHistoricalDataClient, StockDataStream, CryptoDataStream,NewsDataStream, or OptionDataStream.

Broker API

To use the Broker API, you will need to sign up for a broker account and retrieve your Broker API keys. The API keys can be found on the dashboard once you’ve logged in. Alpaca also provides a sandbox environment to test out Broker API. To use the sandbox mode, provide your sandbox keys. Once you have your keys, you can pass them into BrokerClient to get started.

Usage

Alpaca’s APIs allow you to do everything from building algorithmic trading strategies to building a full brokerage experience for your own end users. Here are some things you can do with Alpaca-py.

To view full descriptions and examples view the documentation page.

Market Data API: Access live and historical market data for 5000+ stocks, 20+ crypto, and options.

Trading API: Trade stock and crypto with lightning fast execution speeds.

Broker API & Connect: Build investment apps - from robo-advisors to brokerages.

Broker API Example

Listing All Accounts

The BrokerClient.list_accounts method allows you to list all the brokerage accounts under your management. The method takes an optional parameter search_parameters which requires a ListAccountsRequest object. This parameter allows you to filter the list of accounts returned.

from alpaca.broker.client import BrokerClient
from alpaca.broker.requests import ListAccountsRequest
from alpaca.broker.enums import AccountEntities

broker_client = BrokerClient('api-key', 'secret-key')

# search for accounts created after January 30th 2022.
# Response should contain Contact and Identity fields for each account.
filter = ListAccountsRequest(
                    created_after=datetime.datetime.strptime("2022-01-30", "%Y-%m-%d"),
                    entities=[AccountEntities.CONTACT, AccountEntities.IDENTITY]
                    )

accounts = broker_client.list_accounts(search_parameters=filter)

Trading API Example

Submitting an Order

To create an order on Alpaca-py you must use an OrderRequest object. There are different OrderRequest objects based on the type of order you want to make. For market orders, there is MarketOrderRequest, limit orders have LimitOrderRequest, stop orders StopOrderRequest, and trailing stop orders have TrailingStopOrderRequest. Each order type have their own required parameters for a successful order.

from alpaca.trading.client import TradingClient
from alpaca.trading.requests import MarketOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce

trading_client = TradingClient('api-key', 'secret-key')


# preparing order data
market_order_data = MarketOrderRequest(
                      symbol="BTC/USD",
                      qty=0.0001,
                      side=OrderSide.BUY,
                      time_in_force=TimeInForce.DAY
                  )

# Market order
market_order = trading_client.submit_order(
                order_data=market_order_data
                )

Market Data API Example

Querying Historical Bar Data

You can request bar data via the HistoricalDataClients. In this example, we query daily bar data for “BTC/USD” and “ETH/USD” since July 1st 2022. You can convert the response to a multi-index pandas dataframe using the .df property. There are StockHistoricalDataClient and OptionHistoricalDataClient that you also could use to fetch equity/options historical data.

from alpaca.data.historical import CryptoHistoricalDataClient
from alpaca.data.requests import CryptoBarsRequest
from alpaca.data.timeframe import TimeFrame
from datetime import datetime

# no keys required for crypto data
client = CryptoHistoricalDataClient()

request_params = CryptoBarsRequest(
                        symbol_or_symbols=["BTC/USD", "ETH/USD"],
                        timeframe=TimeFrame.Day,
                        start=datetime.strptime("2022-07-01", '%Y-%m-%d')
                        )

bars = client.get_crypto_bars(request_params)

# convert to dataframe
bars.df

Querying News Data

You can query news data via the NewsClient. In this example, we query news data for “TSLA” since July 1st 2022. You can convert the response to a pandas dataframe using the .df property.

from alpaca.data.historical.news import NewsClient
from alpaca.data.requests import NewsRequest
from datetime import datetime

# no keys required for news data
client = NewsClient()

request_params = NewsRequest(
                        symbols="TSLA",
                        start=datetime.strptime("2022-07-01", '%Y-%m-%d')
                        )

news = client.get_news(request_params)

# convert to dataframe
news.df

Options Trading

We're excited to support options trading! Use this section to read up on Alpaca's options trading capabilities. For more details, please refer to our documentation page for options trading

There is an example jupyter notebook to explain methods of alpaca-py for options trading.

Jupyter Notebook Library

Explore examples for stocks, options, and crypto using alpaca-py. Notebooks for each asset class are provided in their respective directories!

Metadata

Release files for alpaca-py 0.44.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for alpaca-py 0.44.0
File Size Uploaded Provenance
alpaca_py-0.44.0.tar.gz 103.6 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for alpaca-py 0.44.0
File Interpreter ABI Platform
alpaca_py-0.44.0-py3-none-any.whl Python 3 none any Details

Total release size: 232.5 kB

Release files / alpaca_py-0.44.0.tar.gz

Download URL alpaca_py-0.44.0.tar.gz
Size 103.6 kB
Tags Source
SHA-256 checksum
How to use checksums
5388715b67b51ad30fa07308e89299d48b19bed65b81013b8a1158fa5837337b
BLAKE2b-256 checksum
How to use checksums
2db799f09835590f2a3fbdb82abf72d81a199a7aca6d0335a6bc6ec057fc2792
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.4.1 CPython/3.13.1 Linux/6.17.0-1020-azure

Release files / alpaca_py-0.44.0-py3-none-any.whl

Download URL alpaca_py-0.44.0-py3-none-any.whl
Size 128.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b54673f967c0c814a5e0223cbb0211a5d9d75a8d107e792872b14e5bae957c03
BLAKE2b-256 checksum
How to use checksums
8e9e69a2d867988578d6f9e52e35d435d8a43296257cf590fb881a3752de7651
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.4.1 CPython/3.13.1 Linux/6.17.0-1020-azure

Security for alpaca-py 0.44.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.44.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page