Trading Systems & Portfolios
Relevant source files
The following files were used as context for generating this wiki page:
AlphaPy provides a comprehensive framework for developing, testing, and managing trading systems and investment portfolios. This system allows speculators and data scientists to move from machine learning model predictions to actionable trading signals and portfolio performance analysis. The framework integrates model-driven signals with traditional technical rules to simulate market operations.
The core of the trading functionality resides in the MarketFlow pipeline, which orchestrates data acquisition, feature engineering, system execution, and portfolio generation. By utilizing classes like System, Portfolio, Position, and Trade, AlphaPy tracks financial states and executes orders across different market fractals.
Sources: alphapy/market_flow.py:215-263, alphapy/portfolio.py:100-165, README.rst:11-18
Trading System Architecture
Trading systems in AlphaPy are defined by entry and exit conditions, holding periods, and scaling rules. A system can be either purely rule-based or model-driven, where signals are derived from classification probabilities (e.g., phigh for long entries and plow for short entries).
The System Class
The System class serves as the blueprint for a trading strategy. It stores the conditional features required for long and short market actions.
| Parameter | Type | Description |
|---|---|---|
name | str | Unique identifier for the system. |
longentry | str | Feature name/condition for a long entry signal. |
shortentry | str | Feature name/condition for a short entry signal. |
longexit | str | Feature name/condition for a long exit signal. |
shortexit | str | Feature name/condition for a short exit signal. |
holdperiod | int | Fixed number of bars to hold a position. |
scale | bool | Whether to add to an existing position on new signals. |
Sources: alphapy/system.py:46-121, alphapy/market_flow.py:97-124
Trading Signal Logic
The trade_system function evaluates these conditions against price data. If a model is utilized, AlphaPy incorporates prediction probabilities into the price frame to evaluate signals like "probability >= 0.7".
The diagram shows the logic flow for a single price bar within the trade_system function.
Sources: alphapy/system.py:145-256, alphapy/market_flow.py:133-140
Portfolio Management
The Portfolio module manages capital allocation, position tracking, and performance valuation. It implements a rigorous accounting structure to handle trades and maintain the net value of all holdings.
Portfolio and Position Structure
A Portfolio consists of multiple Position objects. Each Position tracks its own cost basis, current value, and list of executed Trade objects.
The class diagram illustrates the relationship between the Portfolio, its individual Positions, and the underlying Trades.
Sources: alphapy/portfolio.py:100-165, alphapy/portfolio.py:195-256
Performance Metrics
Portfolios are valued periodically using the valuate_portfolio function, which calculates:
- Net Profit/Return: Performance since the previous valuation.
- Total Profit/Return: Performance since inception.
- Cost Basis: Calculated as the total value of all trades divided by the total shares traded.
Sources: alphapy/portfolio.py:382-414, alphapy/portfolio.py:488-531
Execution and Sizing
AlphaPy supports dynamic position sizing and automated trade execution. The exec_trade function determines the appropriate trade size based on portfolio settings.
Allocation Rules
Trade allocation is governed by the allocate_trade function, which checks for capital restrictions:
- Restricted Mode: Ensures that trades do not exceed free margin (calculated as
(cash - cashreserve) / margin). - Dynamic Sizing: If
posbyis configured (e.g., 'close'), trade size is calculated as(portfolio_value * fixed_fraction) / current_price. - Kick-out and Stop-loss: Automatically reduces positions based on performance criteria or maximum loss thresholds.
Sources: alphapy/portfolio.py:537-578, alphapy/portfolio.py:656-708, alphapy/portfolio.py:418-450
Order Types
AlphaPy uses a standard set of order identifiers defined in the Orders class:
le: Long Entryse: Short Entrylx: Long Exitsx: Short Exitlh: Long Exit (Hold Period)sh: Short Exit (Hold Period)
Sources: alphapy/globals.py:210-234
Data Flow: From Pipeline to Portfolio
The integration between the machine learning model and the trading portfolio follows a sequential data flow within market_flow.py.
The sequence diagram details how signals move from the analysis pipeline into the portfolio accounting system and finally to disk for analysis.
Sources: alphapy/market_flow.py:215-263, alphapy/portfolio.py:711-840, alphapy/system.py:270-340
Performance Analysis Integration
AlphaPy generates specialized files for use with Quantopian's pyfolio library. These are saved in the systems directory within the project path:
- Returns Frame: Daily percentage returns of the portfolio.
- Positions Frame: Daily market value of each position plus cash.
- Transactions Frame: Record of every trade amount, price, and symbol.
Sources: alphapy/portfolio.py:808-837, README.rst:43-52
Summary
The Trading Systems & Portfolios module transforms AlphaPy from a prediction engine into a full-cycle backtesting environment. By separating the logic of signal generation (System) from capital management (Portfolio), it provides a modular architecture where users can test complex strategies. The system's ability to output standardized data frames ensures compatibility with external visualization tools while maintaining internal consistency through rigorous position valuation and trade allocation logic.
Sources: alphapy/system.py, alphapy/portfolio.py, alphapy/market_flow.py