STONKS Pipeline: Modular Trading Framework
- STONKS Pipeline is an object-oriented framework that unifies data collection, preprocessing, feature engineering, signal generation, backtesting, evaluation, and deployment.
- It enables rapid prototyping and robust backtesting of trading algorithms like SMA crossover, VWAP, sentiment analysis, and statistical arbitrage across equity and crypto markets.
- The modular design leverages a uniform pandas DataFrame interface and dedicated Python classes to ensure seamless strategy development, extensibility, and live deployment.
The STONKS Pipeline is an end-to-end, object-oriented framework for rapidly prototyping, backtesting, evaluating and—ultimately—deploying systematic trading strategies against both equity and crypto markets. It was introduced as part of a generally applicable pipeline for designing, programming, and evaluating the algorithmic trading of stock and crypto assets, and was demonstrated through four conventional algorithms: the moving average crossover, volume-weighted average price, sentiment analysis, and statistical arbitrage algorithms. The framework is implemented through object-oriented programming in Python3 and is presented as open-source software for future academic research and applications (Zhang et al., 2022).
1. System definition and architectural scope
The STONKS Pipeline decomposes cleanly into seven sequential stages: Data Collection, Preprocessing, Feature Engineering, Signal Generation & Model Design, Backtesting, Evaluation & Reporting, and Deployment (Zhang et al., 2022). Its organizing principle is modular encapsulation: each stage is represented by a dedicated class hierarchy, with a uniform pandas-style DataFrame interface used across modules. This yields a reusable skeleton for systematic trading research in which data sources, indicators, strategies, and execution logic can be substituted without rewriting the full workflow (Zhang et al., 2022).
The framework is explicitly designed for both equity and crypto markets. In the paper’s illustrations, the Simple Moving Average Crossover (SMA-Crossover) and Volume-Weighted Average Price (VWAP) strategies serve as case studies, while Sentiment Analysis and Statistical Arbitrage are presented as direct extensions. This design places STONKS at the intersection of financial data engineering, rule-based signal generation, and backtest-oriented quantitative research rather than treating each strategy as an isolated script.
| Stage | Function |
|---|---|
| 1. Data Collection | Acquire market data through a DataHandler |
| 2. Preprocessing | Handle missing values, alignment, resampling, normalization |
| 3. Feature Engineering | Compute indicator columns |
| 4. Signal Generation & Model Design | Emit discrete trading signals |
| 5. Backtesting | Simulate portfolio evolution |
| 6. Evaluation & Reporting | Compute metrics and generate dashboards |
| 7. Deployment | Run the same pipeline in live mode |
A plausible implication is that the framework is intended to reduce the fragmentation described in the paper as “disconnected information islands” by imposing a common software and methodological structure on heterogeneous trading workflows (Zhang et al., 2022).
2. Data model and preprocessing workflow
In the Data Collection stage, traditional equities and intraday data are retrieved via the Alpha Vantage REST API. The specification includes TIME_SERIES_DAILY for stocks and spot crypto, providing close and volume, and the TECHNICAL_INDICATOR endpoint for VWAP on stocks. For spot crypto tick-level data, where VWAP is unavailable, the same API’s raw time-series calls are used (Zhang et al., 2022).
The core data abstraction is the DataHandler object. Each DataHandler encapsulates a symbol and an interval such as 1d or 5 min, and provides a pandas-style DataFrame with the columns Date, Open, High, Low, Close, Volume, plus VWAP where available. The class skeleton given in the description is:
1
Preprocessing performs missing-value handling through forward-fill or drop, timestamp alignment across multiple symbols for multi-asset strategies, and resampling of intraday bars when needed, such as 1-min → 5-min. The stage also includes normalization or log-returns for certain strategies, notably pairs trading (Zhang et al., 2022).
The framework’s domain adaptation rules distinguish stock and crypto operation. VWAP from the API is stock-only, so crypto VWAP must be computed manually. Crypto markets run 24/7, requiring the DataHandler to handle weekends and holidays seamlessly. Tick-level or 1-min data in crypto is often rate-limited, and the pipeline automatically resamples in response (Zhang et al., 2022). This suggests that STONKS treats data heterogeneity as a first-class systems concern rather than as a preprocessing afterthought.
3. Indicator modules and engineered features
Feature Engineering is implemented through four “Indicator” modules, each of which accepts cleaned price and volume series and returns a new column of computed features (Zhang et al., 2022). The architecture treats feature computation as a separable layer between raw market data and strategy logic.
For the Simple Moving Average, the pipeline uses
with short-window and long-window , for example 50 and 200, producing the output columns and (Zhang et al., 2022).
For VWAP, the intraday formula is
When the API does not supply VWAP, as in crypto, the pipeline computes it on the fly (Zhang et al., 2022).
The Sentiment Analysis extension uses Twitter or Reddit posts scraped by snscrape or another wrapper. Sentiment is scored by the VADER rule-based model, yielding a polarity score , and aggregated to hourly or daily average sentiment as the feature (Zhang et al., 2022).
The Statistical Arbitrage or Pairs Trading extension operates on two cointegrated symbols and . It fits an OLS spread
0
with 1 estimated by the Engle-Granger two-step procedure:
- OLS: 2
- Test 3 for stationarity (ADF)
The spread is then standardized by the rolling z-score
4
An implementation note in the framework specifies that each indicator is its own class, exemplified by SMAIndicator with a compute method returning a DataFrame (Zhang et al., 2022). This encapsulation makes feature definitions explicit software objects rather than implicit transformations embedded inside strategy code.
4. Signal generation and strategy logic
Every Strategy object receives the original price DataFrame plus one or more engineered features and emits a discrete buy/sell/hold signal column 5 (Zhang et al., 2022). This formal separation between indicator computation and signal emission is central to the framework’s modularity.
For the SMA-Crossover strategy, the buy rule is triggered when 6 and yesterday 7; the sell rule is triggered when 8 and yesterday 9 (Zhang et al., 2022). In LaTeX form,
0
For the VWAP Crossover strategy, the buy rule is Close_t > VWAP_t with Close_{t−1} ≤ VWAP_{t−1}, and the sell rule is Close_t < VWAP_t with Close_{t−1} ≥ VWAP_{t−1} (Zhang et al., 2022).
The sentiment extension defines threshold-based actions: buy when 1 crosses above a threshold 2 and sell when it crosses below a threshold 3 (Zhang et al., 2022). The pairs-trading extension enters a long spread when 4, enters a short spread when 5, and exits both positions when 6 (Zhang et al., 2022).
These rules are conventional rather than model-free. A plausible implication is that STONKS is structured to make the transition from hand-crafted technical rules to more complex predictive models straightforward, because the signal interface is already standardized around discrete trading actions.
5. Backtesting, evaluation, and reporting
All strategies are wrapped by a reusable Backtester class. The key parameters identified in the description are initial_capital, position_sizing, transaction_cost, and maximum position capacity. The examples given are USD 10,000 for SMA, USD 100,000 for VWAP, all-in or fixed-lot sizing, transaction costs as flat fee or percentage, and a 0.1 % fee in the ETH example, with capacity such as 1 lot per trade (Zhang et al., 2022).
The provided pseudocode shows a sequential account simulation in which cash and holdings are updated when a signal is emitted, with purchase quantity determined by available cash and sale proceeds net of fees:
2
After backtesting, the pipeline computes Return on Investment,
7
and the daily Sharpe Ratio,
8
where 9 is the risk-free rate and is often set to zero for crypto (Zhang et al., 2022). Additional extendable metrics are max drawdown, win/loss ratio, and Calmar ratio.
The Visualizer module produces three dashboard panels: price with buy/sell arrows, cash and position value over time, and cumulative returns for strategy versus buy-and-hold. The paper states that all figures identified as Figures 3.1.a–d and 3.2.a–d are produced by this Visualizer (Zhang et al., 2022). This reporting layer places signal interpretation, portfolio accounting, and comparative visualization inside the same pipeline rather than distributing them across separate notebooks or scripts.
6. Deployment, extensibility, and nomenclature
The same Pipeline object can be called in “live” mode. In that mode, DataHandler fetches the most recent bar via API, indicators are recomputed on the rolling window, the strategy emits a new signal at time 0, and ExecutionManager sends orders through a broker API (Zhang et al., 2022). Because each stage is encapsulated in an OOP class, the framework states that it is trivial to swap in or out modules: a new data source by subclassing DataHandler, a new indicator such as EMA or RSI by subclassing Indicator, a new strategy by subclassing Strategy, and new execution logic such as limit orders or pyramiding by subclassing Backtester or ExecutionManager (Zhang et al., 2022).
The best practices listed for extension are also software-architectural: keep modules single-purpose and interchangeable, centralize all parameters in a YAML/JSON config so the same codebase can backtest multiple experiments in parallel, leverage vectorized pandas/numpy operations in indicators and backtester loops for speed, write small unit tests around each module, and use logging hooks to record each trade execution in live mode for later auditing (Zhang et al., 2022).
Risk controls are treated as domain-specific modifications rather than universal defaults. The framework notes that crypto volatility often requires tighter stop-loss or smaller position sizes, and that fees and slippage differ widely between an exchange’s spot and block trades (Zhang et al., 2022). This suggests that STONKS is a framework for experimentation and systematic comparison, not a claim that one fixed parameterization transfers unchanged across asset classes.
The name “STONKS” is not unique in the arXiv literature. Unrelated works use the same acronym for a stochastic finite-volume method for gas pipeline network flows (Kazi et al., 2024) and for the “Search for Transient Objects in New detections using Known Sources” in XMM-Newton transient astronomy (Quintin et al., 2024), including subsequent observational applications and operational descriptions (Webbe et al., 27 Jan 2026, Webb et al., 21 Nov 2025). In the context of algorithmic trading, however, STONKS refers specifically to the seven-stage data science pipeline described above (Zhang et al., 2022).