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 is organized into modular packages, primarily dealing with stock trading, interactions with APIs (mainly Alpaca), and data handling. The trading modules handle various operations like watchlists, positions, accounts, news, and market interactions. |
๐ฉ | Code Quality | The codebase appears to follow a structured and modular approach with the usage of dataclasses for models ensuring clarity. The presence of utility functions indicates clean separation of concerns for data transformation tasks. |
๐ | Documentation | Documentation includes code comments and descriptive docstrings for functions and classes. The pyproject.toml and requirements.txt files provide clear dependency management information. However, project-wide documentation and usage examples may need enhancement. |
๐ | Integrations | The code integrates with prominent financial data services like Yahoo Finance and Benzinga. It also utilizes Prophet for stock prediction and leverages the Alpaca trading API for executing trading operations. Matplotlib and Plotly are employed for data visualization. |
๐งฉ | Modularity | The project is highly modular with distinct packages and sub-packages handling specific responsibilities such as historical data retrieval, predictive analysis, trading functions, and account management. Reusability is evident through the use of utility modules. |
๐งช | Testing | Utilizes continuous integration via GitHub Actions, as seen in the .github/workflows/test-package.yaml workflow file. Testing practices appear to include automated tests for multiple environments which help catch issues early in the development process. |
โก๏ธ | Performance | Performance optimization measures include efficient HTTP request handling with retry mechanisms. The Prophet model ensures efficient stock prediction by leveraging historical data with advanced forecasting techniques. Explicit attention to modular detailed design suggests minimalistic performance overheads. |
๐ก๏ธ | Security | Security measures such as data validation within utility functions and thorough modeling for user and trading data are in place. However, explicit security practices regarding API key management or data encryption could be better detailed. |
๐ฆ | Dependencies | Key external libraries include pandas for data manipulation, requests for HTTP communication, matplotlib and plotly for visualization, beautifulsoup4 for web scraping, numpy for numerical operations, and prophet for predictive modeling. |
๐ | Scalability | The architecture supports scalable operations given its modularity and use of robust libraries like pandas and numpy . The reliance on scalable cloud-hosted APIs such as Alpaca further enhances the capability to handle increased load. |
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
โ โโโ news.py
โ โโโ orders.py
โ โโโ positions.py
โ โโโ recommendations.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_news.py
โโโ test_orders.py
โโโ test_positions.py
โโโ test_recommendations.py
โโโ test_watchlists.py
โโโ test_watchlists2.py
Modules
.
File | Summary |
---|---|
requirements.txt | Specify all required dependencies for the py-alpaca-api project, ensuring compatibility with Python versions 3.12 to 4.0. Critical dependencies facilitate functionalities for data visualization, time series analysis, HTTP requests, date manipulation, and prophet, among others, reinforcing seamless integrations and optimal performance across various platforms and environments. |
pyproject.toml | Defines metadata and dependency management for the py-alpaca-api project using Poetry, ensuring compatibility and functionality with specified Python and library versions, alongside configuring development, testing, and documentation dependencies for streamlined project maintenance and collaboration. Serves as the foundational setup for the project's environment. |
src.py_alpaca_api.trading
File | Summary |
---|---|
watchlists.py | Facilitates complete management of watchlists in the trading module, handling operations such as retrieval, creation, updating, deletion, and manipulation of assets, seamlessly integrating with HTTP requests and watchlist model handling for comprehensive API interaction. Part of a structured trading architecture within the py-alpaca-api repository. |
recommendations.py | Provide stock recommendations and generate sentiment analysis for given symbols, integrating with external APIs and popular stock data sources like Yahoo Finance. Enhance trading strategy modules in the parent repositorys architecture, supporting informed investment decisions for users. |
positions.py | Manage user positions, providing retrieval and organization of Alpaca trading account positions. Enhance data with comprehensive market details, sorting capabilities, and support for tracking cash positions alongside asset positions, ensuring accurate portfolio analysis and streamlined access to current trading statuses. |
orders.py | Py-alpaca-api/src/py_alpaca_api/http/requests.pyThe requests.pyfile is a critical component within the py_alpaca_apipackage of the repository. This file primarily handles the HTTP requests specific to the Alpaca API, facilitating communication between the user's application and Alpaca's endpoint services. It encapsulates the necessary methods to perform various operations such as querying market data, submitting orders, and retrieving account information. By abstracting and managing these interactions, requests.pyserves as a foundational module that enables other parts of the repository, such as models and higher-level structures, to function seamlessly without directly managing the complexities of HTTP transactions. Overall, it plays a pivotal role in ensuring that the API communicates effectively and reliably with Alpacas systems, serving as an backbone for the integration functionalities of the entire py-alpaca-api` repository. |
news.py | Retrieves and processes financial news articles related to specific market symbols from sources like Yahoo Finance and Benzinga, integrating them into the trading module to provide real-time, relevant news updates. Enables article scraping, HTML stripping, content truncation, and organized presentation with options to filter by date and content presence. |
market.py | Facilitates interaction with the market data endpoints. Provides methods to retrieve the current market clock and market calendar within a specified date range, returning structured data. This is essential for ensuring the core trading functionality operates with accurate market timing, enhancing decision-making and automation capabilities. |
account.py | Manage user account information, activities, and portfolio history within the Alpaca API trading module. Offer seamless data retrieval, including user account details, activity logs filtered by type and date, and detailed portfolio history with configurable periods, timeframes, and intraday reporting, presented in a structured and analyzable format. |
src.py_alpaca_api.stock
File | Summary |
---|---|
screener.py | Streamlines the identification and filtering of stock market gainers and losers based on specific criteria such as price, change, volume, and trade count. Leverages Alpaca Data API to retrieve and evaluate stocks, efficiently categorizing them for further decision-making processes in trading applications. |
predictor.py | Predicts future stock gainers by leveraging historical stock data and the Prophet model for forecasting. Collects data on previous day losers, trains a model, and generates a forecast to identify stocks expected to yield high future returns, aiding in strategic stock trading decisions. |
history.py | Retrieve and preprocess historical stock data, ensuring the asset is a valid stock before fetching. Offer end-users rich, structured financial data in customizable parameters to aid in stock analysis within the overarching Alpaca API-based trading platform architecture. |
assets.py | Provide functionality for retrieving asset information from the Alpaca API. Supports fetching individual asset details and obtaining a filtered DataFrame of multiple assets, focusing on active, fractionable, and tradable US equities while excluding specified exchanges. Integrates with asset models to ensure data consistency. |
src.py_alpaca_api.models
File | Summary |
---|---|
watchlist_model.py | Facilitates the conversion and management of watchlist data for the Alpaca API by defining the WatchlistModel data class, processing asset lists into AssetModel objects, and providing functions to transform raw data dictionaries into fully-formed WatchlistModel instances, thus ensuring compatibility with the repositorys overall architecture. |
position_model.py | Model investor positions, capturing attributes like asset details, market value, and performance metrics. Ensure seamless data transformation through a utility function that converts dictionaries into structured PositionModel instances. Central to monitoring and analyzing financial portfolios within the broader repository focused on trading and stock data management. |
order_model.py | Manages the definition and creation of order data models within the API context. Facilitates the processing, conversion, and organization of order-related information, supporting detailed order data extraction and representation in a standardized model crucial for trading operations and strategies in the parent repository. |
model_utils.py | Facilitates data extraction and transformation for various data models within the Alpaca API by providing utility functions to retrieve and process dictionary values. Ensures consistent and type-safe data parsing for integers, floats, strings, and dates, optimizing data handling across the repositorys different model layers. |
clock_model.py | Define a data model for market clock information, encapsulating the market status and key timestamps. Include functions for creating model instances from dictionaries, facilitating structured and efficient data handling within the broader API. |
asset_model.py | Provide a structured abstraction for financial asset data, utilizing dataclass to define essential asset attributes. Facilitate transformation of data dictionaries to asset model instances, aiding in seamless interaction and manipulation within the broader trading API ecosystem. Boosts integration efficiency with other models and API endpoints. |
account_model.py | Define and structure the properties and behavior of account-related data within the context of the API. Enables conversion of dictionary data into AccountModel instances for seamless data management and interaction with Alpacaโs trading platform. |
account_activity_model.py | Models account activity data in a structured format, enabling easy conversion from dictionary inputs. Facilitates efficient data encapsulation and retrieval for handling account-related events within the trading application. Integrates with existing model utilities for standardized processing and consistency within the repositoryโs architecture. |
src.py_alpaca_api.http
File | Summary |
---|---|
requests.py | Handle HTTP requests with configurable retry strategies, ensuring resilient communication with APIs, essential for robust data exchanges and integrations within the py-alpaca-api repository. |
.github.workflows
File | Summary |
---|---|
test-package.yaml | Define the continuous integration workflow for the repository by automating the testing process. Configure multi-environment tests for the software package to ensure reliability and catch issues early by automatically running tests on every code push or pull request. |
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.8.tar.gz
.
File metadata
- Download URL: py_alpaca_api-2.1.8.tar.gz
- Upload date:
- Size: 39.1 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 | db70cb95877d1981fe85127a054cbf6b5ff3732020ff7633771b90b356a2e776 |
|
MD5 | 2fa62472e6867c9ef0422b3ed7222092 |
|
BLAKE2b-256 | 5595fe29cad7979920b6f5963ffc0e0e47ad5056781edf302ec20045122a9318 |
File details
Details for the file py_alpaca_api-2.1.8-py3-none-any.whl
.
File metadata
- Download URL: py_alpaca_api-2.1.8-py3-none-any.whl
- Upload date:
- Size: 41.9 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 | 41c60684781e817d9dbd32a623aa9b9537b874374c0227691d03d7c02eba7b4a |
|
MD5 | d490c23f0e3b64fbedf5717c31446871 |
|
BLAKE2b-256 | b7732d73d2d088c5fdaf55fffbcda3fc4c42aa648e1bceda8203a6f9be7e3a66 |