Trading Model Example Setup
Relevant source files
The following files were used as context for generating this wiki page:
The Trading Model Example Setup in AlphaPy provides a template for building predictive financial models and executing automated trading systems. It utilizes the MarketFlow pipeline to ingest market data, apply feature engineering, train machine learning models, and generate trade signals through a defined backtesting system. The primary goal is to transform raw price data into actionable probabilities that drive entry and exit orders within a managed portfolio.
This setup is controlled through YAML configuration files (market.yml, model.yml, and algos.yml) which define everything from the data source and technical features to the specific machine learning algorithms (e.g., Random Forest) and portfolio constraints. The architecture separates data retrieval, analysis, and system execution to allow speculators to test various hypotheses efficiently.
Sources: alphapy/market_flow.py:175-185, alphapy/examples/Trading Model/config/model.yml:1-35
Pipeline Architecture and Data Flow
The Trading Model follows a structured flow starting from raw data ingestion and ending with portfolio generation. The market_pipeline function coordinates these steps by interacting with the Model, Group, and System classes.
MarketFlow Execution Steps
- Data Retrieval: Historical data is fetched based on the
market.ymlconfiguration (e.g., from Yahoo Finance, IEX, or local CSV files). - Feature Application: Technical indicators and user-defined variables are applied to the data frames.
- Analysis and Modeling: If
create_modelis enabled, the pipeline trains a model (e.g., a classifier to predict if a stock is "over" a specific range). - System Execution: The
Systemclass evaluates entry/exit conditions, often using model probabilities (likephighfor probabilities >= 0.7). - Portfolio Generation: Trade lists are converted into returns, positions, and transaction records.
The following diagram illustrates the flow from configuration to portfolio results:
The diagram shows the sequence of operations within the MarketFlow pipeline, emphasizing the transition from data preparation to strategy execution.
Sources: alphapy/market_flow.py:175-256, alphapy/data.py:532-628
Configuration and Components
The setup relies on specific classes and data structures defined in the core framework to manage the complexity of financial data and machine learning.
Key Classes and Structures
- Model: Unifies algorithms, specifications, and metrics. It stores predictions (
preds), probabilities (probas), and feature importances. - System: Defines the trading logic, including
longentry,shortentry, andholdperiod. - Portfolio: Tracks the state of all positions, cash balance, and ROI (Return on Investment).
- Space: A namespace object defining the subject (e.g., 'stock'), schema (e.g., 'yahoo'), and fractal (e.g., '1d').
Sources: alphapy/model.py:72-126, alphapy/system.py:65-95, alphapy/portfolio.py:92-162
Model Configuration Example
The model.yml file for the Trading Model example specifically configures a Random Forest (RF) classifier to target a custom variable rrover.
| Parameter | Type | Value | Description |
|---|---|---|---|
target | String | rrover | The variable the model tries to predict. |
algorithms | List | ['RF'] | The ML algorithms to utilize. |
sampling:method | Enum | under_random | Technique for handling imbalanced classes. |
scoring_function | String | roc_auc | Metric used to evaluate and select the best model. |
cv_folds | Integer | 3 | Number of cross-validation folds. |
Sources: alphapy/examples/Trading Model/config/model.yml:18-50, alphapy/model.py:133-250
Trading Logic and Signal Generation
Signals are generated in the trade_system function. A system can be "model-driven" if its entry or exit conditions reference the internal variables phigh (high probability of target) or plow (low probability).
Signal Evaluation Logic
The system iterates through price data and checks conditions:
- Long Entry (
le): Triggered by thelongentrycondition. If a short position exists, it is closed first. - Short Entry (
se): Triggered byshortentry. - Exit Conditions: Triggered by
longexit,shortexit, or the expiration of theholdperiod. - Intraday Handling: If the
end_of_dayflag is encountered during intraday trading, all open positions are closed.
This sequence shows how the system evaluates individual bars to generate entries and exits based on predefined conditions.
Sources: alphapy/system.py:157-250, alphapy/market_flow.py:108-112
Feature Engineering and Data Preparation
In the Trading Model example, various technical transformations are applied to the data before training. The market.yml file (and the vmapply function) handles these transformations.
- Feature Selection: The example model drops a large list of columns (e.g.,
open,high,low,volume) to focus on generated features likeruns_testresults. - Variable Mapping: User-defined variables are mapped to conditions. For example,
phighis mapped toprobability >= 0.7. - Technical Treatments: The
model.ymldefines treatments likeruns_testapplied to variables such asrroverortrend.
Sources: alphapy/examples/Trading Model/config/model.yml:7-15, 107-120, alphapy/market_flow.py:215-225
Conclusion
The Trading Model Example Setup demonstrates a complete lifecycle for financial machine learning within AlphaPy. By leveraging the MarketFlow pipeline, it bridges the gap between statistical analysis and active portfolio management. Users can configure complex ensembles and custom trading systems solely through YAML files, while the underlying Python engine handles the robust tasks of data resampling, cross-validation, and transaction recording.
Sources: alphapy/market_flow.py:252-256, alphapy/portfolio.py:695-780