{"id":17377211,"url":"https://github.com/alpacahq/alpaca-py","last_synced_at":"2025-05-14T00:07:34.487Z","repository":{"id":37084657,"uuid":"461335313","full_name":"alpacahq/alpaca-py","owner":"alpacahq","description":"The Official Python SDK for Alpaca API","archived":false,"fork":false,"pushed_at":"2025-04-17T03:51:02.000Z","size":2056,"stargazers_count":764,"open_issues_count":77,"forks_count":186,"subscribers_count":47,"default_branch":"master","last_synced_at":"2025-04-21T19:02:09.977Z","etag":null,"topics":["algorithmic-trading","algotrading","alpaca","alpaca-api","brokerage","crypto","equities","finance","market-data","options","python","quant","quantitative-finance","stock-trading","trading"],"latest_commit_sha":null,"homepage":"https://alpaca.markets/sdks/python/getting_started.html","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/alpacahq.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":"CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2022-02-19T23:10:34.000Z","updated_at":"2025-04-19T15:50:40.000Z","dependencies_parsed_at":"2023-02-14T09:45:45.918Z","dependency_job_id":"a05a3aa6-756e-4065-957e-893581a30d37","html_url":"https://github.com/alpacahq/alpaca-py","commit_stats":null,"previous_names":[],"tags_count":80,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alpacahq%2Falpaca-py","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alpacahq%2Falpaca-py/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alpacahq%2Falpaca-py/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alpacahq%2Falpaca-py/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/alpacahq","download_url":"https://codeload.github.com/alpacahq/alpaca-py/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254043777,"owners_count":22005014,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["algorithmic-trading","algotrading","alpaca","alpaca-api","brokerage","crypto","equities","finance","market-data","options","python","quant","quantitative-finance","stock-trading","trading"],"created_at":"2024-10-16T05:01:03.881Z","updated_at":"2025-05-14T00:07:34.472Z","avatar_url":"https://github.com/alpacahq.png","language":"Python","readme":"[![Alpaca-py](https://github.com/alpacahq/alpaca-py/blob/master/docs/images/alpaca-py-banner.png?raw=true)](https://alpaca.markets/docs/python-sdk)\n\n[![Downloads](https://pepy.tech/badge/alpaca-py/month)](https://pepy.tech/project/alpaca-py)\n[![Python Versions](https://img.shields.io/pypi/pyversions/alpaca-py.svg?logo=python\u0026logoColor=white)](https://pypi.org/project/alpaca-py)\n[![GitHub](https://img.shields.io/github/license/alpacahq/alpaca-py?color=blue)](https://github.com/alpacahq/alpaca-py/blob/master/LICENSE.md)\n[![PyPI](https://img.shields.io/pypi/v/alpaca-py?color=blue)](https://pypi.org/project/alpaca-py/)\n\n## Table of Contents\n\n- [About](#about)\n- [Documentation](#documentation)\n- [Installation](#installation)\n- [Update](#update)\n- [What's New?](#whats-new)\n  1.  [Broker API](#broker-api-new)\n  2.  [OOP Design](#oop-design)\n  3.  [Data Validation](#data-validation)\n  4.  [Many Clients](#many-clients)\n- [API Keys](#api-keys)\n  1.  [Trading and Market Data API Keys](#trading-api-keys)\n  2.  [Broker API Keys](#trading-api-keys)\n- [Usage](#usage)\n  1.  [Broker API Example](#broker-api-example)\n  2.  [Trading API Example](#trading-api-example)\n  3.  [Market Data API Example](#data-api-example)\n- [Contributing](https://github.com/alpacahq/alpaca-py/blob/master/CONTRIBUTING.md)\n- [License](https://github.com/alpacahq/alpaca-py/blob/master/LICENSE)\n\n## About \u003ca name=\"about\"\u003e\u003c/a\u003e\n\nAlpaca-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.\n\nLearn more about the API products Alpaca offers at https://alpaca.markets.\n\n## Documentation \u003ca name=\"documentation\"\u003e\u003c/a\u003e\n\nAlpaca-py has a supplementary documentation site which contains references for all clients, methods and models found in this codebase. The documentation\nalso contains examples to get started with alpaca-py.\n\nYou can find the documentation site here: https://alpaca.markets/sdks/python/getting_started.html\n\nYou can also find the API Reference of Alpaca APIs: https://docs.alpaca.markets/reference\n\n## Installation \u003ca name=\"installation\"\u003e\u003c/a\u003e\n\nAlpaca-py is supported on Python 3.8+.  You can install Alpaca-py using pip.\n\nRun the following command in your terminal.\n\n```shell\n  pip install alpaca-py\n```\n\n## Update \u003ca name=\"update\"\u003e\u003c/a\u003e\n\nIf you already have Alpaca-py installed, and would like to use the latest version available...\n\nRun the following command in your terminal:\n\n```shell\n  pip install alpaca-py --upgrade\n```\n\n## What’s New? \u003ca name=\"whats-new\"\u003e\u003c/a\u003e\n\nIf you’ve used the previous python SDK alpaca-trade-api, there are a few key differences to be aware of.\n\n### Broker API \u003ca name=\"broker-api-new\"\u003e\u003c/a\u003e\n\nAlpaca-py lets you use Broker API to start building your investment apps! Learn more at the [Broker](https://docs.alpaca.markets/docs/about-broker-api) page.\n\n### OOP Design \u003ca name=\"oop-design\"\u003e\u003c/a\u003e\n\nAlpaca-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.\n\nSome examples of request models corresponding to methods:\n\n- `GetOrdersRequest` for `TradingClient.get_orders()`\n- `CryptoLatestOrderbookRequest` for `CryptoHistoricalDataClient.get_crypto_latest_orderbook()`\n\n**Request Models Usage Example**\n\nTo get historical bar data for crypto, you will need to provide a `CryptoBarsRequest` object.\n\n```python\nfrom alpaca.data.historical import CryptoHistoricalDataClient\nfrom alpaca.data.requests import CryptoBarsRequest\nfrom alpaca.data.timeframe import TimeFrame\nfrom datetime import datetime\n\n# no keys required for crypto data\nclient = CryptoHistoricalDataClient()\n\nrequest_params = CryptoBarsRequest(\n                        symbol_or_symbols=[\"BTC/USD\", \"ETH/USD\"],\n                        timeframe=TimeFrame.Day,\n                        start=datetime(2022, 7, 1)\n                 )\n\nbars = client.get_crypto_bars(request_params)\n```\n\n### Data Validation \u003ca name=\"data-validation\"\u003e\u003c/a\u003e\n\nAlpaca-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.\n\nHere is a rough example of what is possible.\n\n```python\n\n @app.route('/post_json', methods=['POST'])\n def do_trade():\n     # ...\n\n     order_data_json = request.get_json()\n\n     # validate data\n     MarketOrderRequest(**order_data_json)\n\n     # ...\n```\n\n### Many Clients \u003ca name=\"many-clients\"\u003e\u003c/a\u003e\n\nAlpaca-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.\n\n**Broker API:** `BrokerClient`\n\n**Trading API:** `TradingClient`\n\n**Market Data API:** `StockHistoricalDataClient`, `CryptoHistoricalDataClient`, `NewsClient`, `OptionHistoricalDataClient`, `CryptoDataStream`, `StockDataStream`, `NewsDataStream`, `OptionDataStream`\n\n## API Keys \u003ca name=\"api-keys\"\u003e\u003c/a\u003e\n\n### Trading and Market Data API \u003ca name=\"trading-api-keys\"\u003e\u003c/a\u003e\n\nIn 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`.\n\n### Broker API \u003ca name=\"broker-api-keys\"\u003e\u003c/a\u003e\n\nTo 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.\n\n## Usage \u003ca name=\"usage\"\u003e\u003c/a\u003e\n\nAlpaca’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.\n\nTo view full descriptions and examples view the [documentation page](https://alpaca.markets/sdks/python/).\n\n**Market Data API**: Access live and historical market data for 5000+ stocks, 20+ crypto, and options.\n\n**Trading API**: Trade stock and crypto with lightning fast execution speeds.\n\n**Broker API \u0026 Connect**: Build investment apps - from robo-advisors to brokerages.\n\n### Broker API Example \u003ca name=\"broker-api-example\"\u003e\u003c/a\u003e\n\n**Listing All Accounts**\n\nThe `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.\n\n```python\nfrom alpaca.broker.client import BrokerClient\nfrom alpaca.broker.requests import ListAccountsRequest\nfrom alpaca.broker.enums import AccountEntities\n\nbroker_client = BrokerClient('api-key', 'secret-key')\n\n# search for accounts created after January 30th 2022.\n# Response should contain Contact and Identity fields for each account.\nfilter = ListAccountsRequest(\n                    created_after=datetime.datetime.strptime(\"2022-01-30\", \"%Y-%m-%d\"),\n                    entities=[AccountEntities.CONTACT, AccountEntities.IDENTITY]\n                    )\n\naccounts = broker_client.list_accounts(search_parameters=filter)\n```\n\n### Trading API Example \u003ca name=\"trading-api-example\"\u003e\u003c/a\u003e\n\n**Submitting an Order**\n\nTo 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.\n\n```python\nfrom alpaca.trading.client import TradingClient\nfrom alpaca.trading.requests import MarketOrderRequest\nfrom alpaca.trading.enums import OrderSide, TimeInForce\n\ntrading_client = TradingClient('api-key', 'secret-key')\n\n\n# preparing order data\nmarket_order_data = MarketOrderRequest(\n                      symbol=\"BTC/USD\",\n                      qty=0.0001,\n                      side=OrderSide.BUY,\n                      time_in_force=TimeInForce.DAY\n                  )\n\n# Market order\nmarket_order = trading_client.submit_order(\n                order_data=market_order_data\n                )\n```\n\n### Market Data API Example \u003ca name=\"data-api-example\"\u003e\u003c/a\u003e\n\n**Querying Historical Bar Data**\n\nYou 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.\n\n```python\nfrom alpaca.data.historical import CryptoHistoricalDataClient\nfrom alpaca.data.requests import CryptoBarsRequest\nfrom alpaca.data.timeframe import TimeFrame\nfrom datetime import datetime\n\n# no keys required for crypto data\nclient = CryptoHistoricalDataClient()\n\nrequest_params = CryptoBarsRequest(\n                        symbol_or_symbols=[\"BTC/USD\", \"ETH/USD\"],\n                        timeframe=TimeFrame.Day,\n                        start=datetime.strptime(\"2022-07-01\", '%Y-%m-%d')\n                        )\n\nbars = client.get_crypto_bars(request_params)\n\n# convert to dataframe\nbars.df\n\n```\n\n**Querying News Data** \u003ca name=\"news-client-example\"\u003e\u003c/a\u003e\n\nYou 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.\n\n```python\nfrom alpaca.data.historical.news import NewsClient\nfrom alpaca.data.requests import NewsRequest\nfrom datetime import datetime\n\n# no keys required for news data\nclient = NewsClient()\n\nrequest_params = NewsRequest(\n                        symbols=\"TSLA\",\n                        start=datetime.strptime(\"2022-07-01\", '%Y-%m-%d')\n                        )\n\nnews = client.get_news(request_params)\n\n# convert to dataframe\nnews.df\n\n```\n\n### Options Trading \u003ca name=\"options-trading\"\u003e\u003c/a\u003e\n\nWe're excited to support options trading! Use this section to read up on Alpaca's options trading capabilities.\nFor more details, please refer to [our documentation page for options trading](https://docs.alpaca.markets/docs/options-trading)\n\nThere is an example jupyter notebook to explain methods of alpaca-py for options trading.\n\n* [jupyter notebook: options trading basic example with alpaca-py](https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-trading-basic.ipynb)\n\n### Jupyter Notebook Library \u003ca name=\"colab-library\"\u003e\u003c/a\u003e\n\nExplore examples for stocks, options, and crypto using alpaca-py. Notebooks for each asset class are provided in their respective directories!\n\n* [Stocks](https://github.com/alpacahq/alpaca-py/blob/master/examples/stocks/README.md)\n* [Crypto](https://github.com/alpacahq/alpaca-py/blob/master/examples/crypto/README.md)\n* [Options](https://github.com/alpacahq/alpaca-py/blob/master/examples/options/README.md)\n* [Multi-Leg Options](https://github.com/alpacahq/alpaca-py/blob/master/examples/options/README.md)","funding_links":[],"categories":["Curated List"],"sub_categories":["API Integrations/Connectors"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falpacahq%2Falpaca-py","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Falpacahq%2Falpaca-py","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falpacahq%2Falpaca-py/lists"}