Python package, for communicating with Alpaca Markets REST API.
Project description
PY-ALPACA-API
Streamline Trading with Seamless Alpaca Integration
Developed with the software and tools below.
Table of Contents
Overview
V2.0.0 is not compatible with previous versions.
Use the V1.0.3 branch for the previous version.
The py-alpaca-api project provides a comprehensive Python interface for executing financial trading operations via the Alpaca API. It enables the management of watchlists, account positions, market data, and stock portfolios. It includes functionalities for order processing, stock screening, and predictive analytics leveraging historical data, enhancing market analysis and trading efficiencies. By abstracting complex API interactions into user-friendly Python modules, the project supports streamlined, data-driven trading decisions, making it a valuable tool for both developers and traders aiming for effective financial market engagement.
This project is mainly for fun and my personal use. Hopefully others find it helpful as well. Alpaca has a great Python SDK that provides a robust API interface, just more complex than I need for my uses. Checkout it out here Alpaca-py.
Features
Feature | Description | |
---|---|---|
โ๏ธ | Architecture | The project has a modular architecture interfacing cleanly with Alpaca's financial APIs. It contains well-defined components for trading, stock management, and data analysis. |
๐ฉ | Code Quality | The code is well-structured, follows consistent styling standards (possibly PEP 8), and uses code analysis tools like ruff for maintaining quality. |
๐ | Documentation | Significant documentation is present in code and configuration files, though expansion on code usage examples could strengthen usability. |
๐ | Integrations | Integrates with Alpaca API, Pandas, and uses Prophesy for data predictions. Utilizes GitHub Actions for CI/CD. |
๐งฉ | Modularity | High level of modularity; each functionality (trading, stock management, data models) isolated for standalone use and simple integration. |
๐งช | Testing | Uses pytest for unit and integration testing supported by GitHub Actions CI workflows, ensuring high code reliability. |
โก๏ธ | Performance | Efficient data handling via Pandas and robust HTTP request management with retry/backoff strategies ensuring performance sustainability. |
๐ก๏ธ | Security | Utilizes HTTP request validation, API key management, and securing communications with retries and backoff strategies for robust data protection. |
๐ฆ | Dependencies | pandas, requests, pendulum, plotly, prophe@appet, ruff, poetry for dependency management, tqdm for progress bar integration. |
๐ | Scalability | Utilizes scalable backend services (Alpaca API), combined with strong modular design to support increased load with simple component duplication/expansion. |
Repository Structure
โโโ py-alpaca-api/
โโโ src
โ โโโ py_alpaca_api
โ โโโ __init__.py
โ โโโ http
โ โ โโโ requests.py
โ โโโ models
โ โ โโโ account_activity_model.py
โ โ โโโ account_model.py
โ โ โโโ asset_model.py
โ โ โโโ clock_model.py
โ โ โโโ model_utils.py
โ โ โโโ order_model.py
โ โ โโโ position_model.py
โ โ โโโ watchlist_model.py
โ โโโ stock
โ โ โโโ __init__.py
โ โ โโโ assets.py
โ โ โโโ history.py
โ โ โโโ predictor.py
โ โ โโโ screener.py
โ โโโ trading
โ โโโ __init__.py
โ โโโ account.py
โ โโโ market.py
โ โโโ orders.py
โ โโโ positions.py
โ โโโ watchlists.py
โโโ tests
โโโ __init__.py
โโโ test_http
โ โโโ test_requests.py
โโโ test_models
โ โโโ test_account_activity_model.py
โ โโโ test_account_model.py
โ โโโ test_asset_model.py
โ โโโ test_clock_model.py
โ โโโ test_order_model.py
โ โโโ test_position_model.py
โ โโโ test_watchlist_model.py
โโโ test_stock
โ โโโ test_assets.py
โ โโโ test_history.py
โ โโโ test_history2.py
โ โโโ test_predictor.py
โ โโโ test_screener.py
โโโ test_trading
โโโ test_account.py
โโโ test_account2.py
โโโ test_orders.py
โโโ test_positions.py
โโโ test_watchlists.py
โโโ test_watchlists2.py
Modules
.
File | Summary |
---|---|
pyproject.toml | Define the projects metadata and configurations, including dependencies, development tools, and documentation settings, ensuring robust setup and maintainability. Serve as the primary configuration file for the packaging and distribution of the py-alpaca-api' Python package, coordinating various aspects of development and build processes. |
src.py_alpaca_api.trading
File | Summary |
---|---|
watchlists.py | Manage watchlists with functionalities to create, retrieve, update, and delete them. Provide methods to add or remove assets within watchlists based on various attributes such as ID or name, integrating seamlessly with the Alpaca API to facilitate streamlined trading operations within the repositorys architecture. |
positions.py | Manage and retrieve Alpaca account positions by providing functionality to obtain details for specific positions or all positions in a users account. Utilize pandas DataFrames for data processing, sorting, and modification, ensuring integrations with account and request handling services within the broader repository architecture. |
orders.py | The requests.py file in the src/py_alpaca_api/http directory is responsible for facilitating HTTP request handling within the py-alpaca-api repository. This file plays a critical role in enabling communication between the client interfaces and Alpacas financial APIs by managing the creation, execution, and response processing of API requests. This functionality serves as the backbone for other modules within the project, such as those found in the trading and stock packages, by providing the essential capability to interact with Alpacas platform for activities such as trading operations, market data retrieval, and asset management. |
market.py | Manage market-related data interactions by retrieving the current market clock and market calendar data for specified date ranges, converting responses into structured formats such as models and DataFrames to facilitate easy access and manipulation within the broader ecosystem of the repository. |
account.py | Manages account-related functionalities by retrieving user account information, fetching account activities based on specified filters, and obtaining portfolio history as a pandas DataFrame. Plays a critical role in the trading module by integrating with Alpacas API to provide essential account insights. |
src.py_alpaca_api.stock
File | Summary |
---|---|
screener.py | Provide stock filtering capabilities based on given criteria such as price, volume, and trade count. Identify top gainers and losers by calculating percentage changes over specified timeframes, aiding in market analysis and decision making. Integrate seamlessly into broader Alpaca API, utilizing relevant data endpoints and trading functionalities for holistic stock management. |
predictor.py | Predictor class leverages historical stock data and the Prophet forecasting model to identify potential future stock gainers. It processes previous day stock losers, forecasts their future performance, and returns symbols most likely to achieve significant gains, enhancing stock screening and predictive analytics capabilities within the overall repository architecture. |
history.py | Provide historical stock data by interfacing with the data API, verifying assets as stocks, and preprocessing JSON responses into pandas DataFrames. Enhances the repositorys capacity to fetch detailed and time-specific historical trading information, crucial for analysis, modeling, and prediction tasks within the trading functionality. |
assets.py | Assets management functionality is provided by enabling the retrieval of specific or all US equity assets. It ensures assets are active, fractionable, and tradable, excluding OTC exchanges, integrating seamlessly with the larger trading and analysis system within the repositorys architecture. |
src.py_alpaca_api.models
File | Summary |
---|---|
watchlist_model.py | The watchlist_model.py file defines the WatchlistModel class and functions for converting watchlist data into WatchlistModel instances. It leverages asset processing to facilitate seamless integration within the parent repository, which focuses on managing and interfacing with financial market data and trading functionalities. |
position_model.py | Define and encapsulate data representations for stock positions within the Alpaca trading API. Facilitate conversion between dictionary data and well-structured position objects to support efficient trading operations and analyses in the overall architecture. Enhance data processing consistency and accuracy across the applicationโs trading modules. |
order_model.py | Define and manage the representation of orders, offering utility functions to convert data dictionaries into OrderModel instances and process multi-leg orders for seamless integration into the broader architecture focused on trading activities. |
model_utils.py | Assist data processing within models by providing utility functions for extracting and transforming values from dictionaries into specified types such as strings, integers, floats, and dates. Facilitate the alignment of dictionary data with data class structures to streamline data manipulation and model instantiation within the repository. |
clock_model.py | Facilitates the management and representation of stock market timing data by defining a ClockModel class. This model enables easy extraction and interpretation of market time information, including current market status and future open and close times, to assist with trading operations within the parent repositorys architecture. |
asset_model.py | In the parent repository, enable the management of asset data by defining the structure of AssetModel. Facilitate the conversion of dictionary data into an AssetModel instance, allowing for streamlined interaction with asset-specific information within the larger Alpaca API interface, thus supporting efficient data handling and manipulation. |
account_model.py | Facilitates the representation and manipulation of account data within the repository by providing a structured data model. Ensures accurate and efficient conversion of account information from raw dictionary data to a standard format, essential for maintaining consistency and reliability in account-related operations across the system. |
account_activity_model.py | AccountActivityModel represents user account activities within the Alpaca trading API. It structures essential activity details and allows transformation from raw dictionary data into a cohesive model using validation and extraction utilities, thereby facilitating accurate data handling in broader trading applications. |
src.py_alpaca_api.http
File | Summary |
---|---|
requests.py | Provides structured and resilient HTTP request functionality with retry and backoff mechanisms to handle transient errors. Essential for consistent and reliable communication with the Alpaca API. |
.github.workflows
File | Summary |
---|---|
test-package.yaml | Automatically initiates and manages the CI pipeline for the py-alpaca-api project, ensuring the code quality across updates. Executes tests and validates code changes, supporting continuous integration practices and maintaining the reliability of the projects features as per specified workflows in the GitHub environment. |
Getting Started
System Requirements:
- Python:
version 3.12.0
Installation
From source
- Clone the py-alpaca-api repository:
$ git clone https://github.com/TexasCoding/py-alpaca-api
- Change to the project directory:
$ cd py-alpaca-api
- Install the dependencies:
$ pip install -r requirements.txt
Usage
From source
Run py-alpaca-api using the command below:
import os from py_alpaca_api import PyAlpacaAPI api_key = os.environ.get("ALPACA_API_KEY") api_key = os.environ.get("ALPACA_SECRET_KEY") api = PyAlpacaAPI(api_key=api_key, api_secret=api_secret) # Get the account information for the authenticated account. account = api.trading.account.get() # Get stock asset information asset = api.stock.assets.get("AAPL") # Get stock historical data historical_data = api.stock.history.get_stock_data("AAPL", start="2021-01-01", end="2021-01-10")
Tests
Run the test suite using the command below: Export your API key and secret key as environment variables: Or use .env file (recommended)
$ export ALPACA_API_KEY="YOUR_API_KEY" $ export ALPACA_SECRET_KEY="YOUR_SECRET_KEY" $ pytest
Contributing
Contributions are welcome! Here are several ways you can contribute:
- Report Issues: Submit bugs found or log feature requests for the
py-alpaca-api
project. - Submit Pull Requests: Review open PRs, and submit your own PRs.
- Join the Discussions: Share your insights, provide feedback, or ask questions.
Contributing Guidelines
- Fork the Repository: Start by forking the project repository to your github account.
- Clone Locally: Clone the forked repository to your local machine using a git client.
git clone https://github.com/TexasCoding/py-alpaca-api
- Create a New Branch: Always work on a new branch, giving it a descriptive name.
git checkout -b new-feature-x
- Make Your Changes: Develop and test your changes locally.
- Commit Your Changes: Commit with a clear message describing your updates.
git commit -m 'Implemented new feature x.'
- Push to github: Push the changes to your forked repository.
git push origin new-feature-x
- Submit a Pull Request: Create a PR against the original project repository. Clearly describe the changes and their motivations.
- Review: Once your PR is reviewed and approved, it will be merged into the main branch. Congratulations on your contribution!
License
This project is protected under the MIT License. For more details, refer to the LICENSE file.
Acknowledgments
- List any resources, contributors, inspiration, etc. here.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file py_alpaca_api-2.1.0.tar.gz
.
File metadata
- Download URL: py_alpaca_api-2.1.0.tar.gz
- Upload date:
- Size: 34.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.8.3 CPython/3.12.3 Linux/5.15.153.1-microsoft-standard-WSL2
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | a2a1cd718add076a8a272486ffed94ba1bef2f543da290d11ce43cc5040b6147 |
|
MD5 | e1884b1cd5885037d9ce5c3096433df8 |
|
BLAKE2b-256 | 16c6405ebc4cf7740c8bc5fb00bebdf780c8c833476e5475f65c935c5358baa3 |
File details
Details for the file py_alpaca_api-2.1.0-py3-none-any.whl
.
File metadata
- Download URL: py_alpaca_api-2.1.0-py3-none-any.whl
- Upload date:
- Size: 37.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.8.3 CPython/3.12.3 Linux/5.15.153.1-microsoft-standard-WSL2
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 47e86f49464c943f142ecab95ff30e22ef4c56173ba16d7ecbfcdd9d4a622b49 |
|
MD5 | d795bf5e3a8bd6d7de1ca772600cd78e |
|
BLAKE2b-256 | 8ff7daf91dc848b091c3cda65e8134c1d607ea164921f87e81c7d03da687fe16 |