Skip to main content

Python package, for communicating with Alpaca Markets REST API.

Project description

project-logo

PY-ALPACA-API

Streamline Trading with Seamless Alpaca Integration

GitHub Actions Workflow Status license last-commit repo-top-language repo-language-count

Developed with the software and tools below.

tqdm precommit Poetry Plotly Python GitHub%20Actions pandas


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

  1. Clone the py-alpaca-api repository:
$ git clone https://github.com/TexasCoding/py-alpaca-api
  1. Change to the project directory:
$ cd py-alpaca-api
  1. 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:

Contributing Guidelines
  1. Fork the Repository: Start by forking the project repository to your github account.
  2. Clone Locally: Clone the forked repository to your local machine using a git client.
    git clone https://github.com/TexasCoding/py-alpaca-api
    
  3. Create a New Branch: Always work on a new branch, giving it a descriptive name.
    git checkout -b new-feature-x
    
  4. Make Your Changes: Develop and test your changes locally.
  5. Commit Your Changes: Commit with a clear message describing your updates.
    git commit -m 'Implemented new feature x.'
    
  6. Push to github: Push the changes to your forked repository.
    git push origin new-feature-x
    
  7. Submit a Pull Request: Create a PR against the original project repository. Clearly describe the changes and their motivations.
  8. Review: Once your PR is reviewed and approved, it will be merged into the main branch. Congratulations on your contribution!
Contributor Graph


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.

Return


Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

py_alpaca_api-2.1.0.tar.gz (34.7 kB view hashes)

Uploaded Source

Built Distribution

py_alpaca_api-2.1.0-py3-none-any.whl (37.4 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page