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 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 thepy_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 entirepy-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

  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.5.tar.gz (38.7 kB view hashes)

Uploaded Source

Built Distribution

py_alpaca_api-2.1.5-py3-none-any.whl (41.2 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