---
title: 'STONKS Pipeline: Modular Trading Framework'
url: https://www.emergentmind.com/topics/stonks-pipeline
type: topic
---

# STONKS Pipeline: Modular Trading Framework

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 [2206.14932].

## 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 [2206.14932]. 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 [2206.14932].

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 [2206.14932].

## 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 [2206.14932].

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:

```python
class DataHandler:
    def __init__(self, symbol:str, interval:str, api_key:str): ...
    def fetch_raw(self) -> pd.DataFrame: ...
    def resample(self, to_interval:str) -> pd.DataFrame: ...
```

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 [2206.14932].

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 [2206.14932]. 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 [2206.14932]. The architecture treats feature computation as a separable layer between raw market data and strategy logic.

For the Simple Moving Average, the pipeline uses

$$
\mathrm{SMA}^n_t = \frac{1}{n}\sum_{i=t-n+1}^{t} p_i
$$

with short-window $n_s$ and long-window $n_\ell$, for example 50 and 200, producing the output columns $\mathrm{SMA}^{n_s}_t$ and $\mathrm{SMA}^{n_\ell}_t$ [2206.14932].

For VWAP, the intraday formula is

$$
\mathrm{VWAP}_t = \frac{\sum_{i=1}^{t} P_i \cdot Q_i}{\sum_{i=1}^{t} Q_i}.
$$

When the API does not supply VWAP, as in crypto, the pipeline computes it on the fly [2206.14932].

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 $s_t \in [-1,1]$, and aggregated to hourly or daily average sentiment as the feature $\mathrm{Sent}_t$ [2206.14932].

The Statistical Arbitrage or Pairs Trading extension operates on two cointegrated symbols $X$ and $Y$. It fits an OLS spread

$$
S_t = p^X_t - \beta p^Y_t - \alpha
$$

with $(\alpha,\beta)$ estimated by the Engle-Granger two-step procedure:
1) OLS: $p^X = \alpha + \beta p^Y + \epsilon$  
2) Test $\epsilon$ for stationarity (ADF)

The spread is then standardized by the rolling z-score

$$
z_t = \frac{S_t - \mu_S}{\sigma_S}.
$$

An implementation note in the framework specifies that each indicator is its own class, exemplified by `SMAIndicator` with a `compute` method returning a DataFrame [2206.14932]. 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 $\mathrm{Signal}_t \in \{+1,0,-1\}$ [2206.14932]. 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 $\mathrm{SMA}^{n_s}_t > \mathrm{SMA}^{n_\ell}_t$ and yesterday $\mathrm{SMA}^{n_s}_{t-1} \le \mathrm{SMA}^{n_\ell}_{t-1}$; the sell rule is triggered when $\mathrm{SMA}^{n_s}_t < \mathrm{SMA}^{n_\ell}_t$ and yesterday $\mathrm{SMA}^{n_s}_{t-1} \ge \mathrm{SMA}^{n_\ell}_{t-1}$ [2206.14932]. In LaTeX form,

$$
\mathrm{Signal}_t =
\begin{cases}
+1 & \text{if } \mathrm{SMA}^{n_s}_t > \mathrm{SMA}^{n_\ell}_t \text{ and } \mathrm{SMA}^{n_s}_{t-1} \le \mathrm{SMA}^{n_\ell}_{t-1} \\
-1 & \text{if } \mathrm{SMA}^{n_s}_t < \mathrm{SMA}^{n_\ell}_t \text{ and } \mathrm{SMA}^{n_s}_{t-1} \ge \mathrm{SMA}^{n_\ell}_{t-1} \\
0 & \text{otherwise.}
\end{cases}
$$

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}` [2206.14932].

The sentiment extension defines threshold-based actions: buy when $\mathrm{Sent}_t$ crosses above a threshold $\theta_{\text{buy}}$ and sell when it crosses below a threshold $\theta_{\text{sell}}$ [2206.14932]. The pairs-trading extension enters a long spread when $z_t < -z_{\text{entry}}$, enters a short spread when $z_t > +z_{\text{entry}}$, and exits both positions when $|z_t| < z_{\text{exit}}$ [2206.14932].

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` [2206.14932].

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:

```python
class Backtester:
    def __init__(self, data:pd.DataFrame, signals:pd.Series, capital:float, fee:float): ...
    def run(self) -> pd.DataFrame(account_time_series):
        cash = capital; holdings = 0
        for t in data.index:
            if signals[t] == +1 and cash>0:
                qty = floor(cash / price[t])
                cost = qty*price[t]*(1+fee)
                cash -= cost; holdings += qty
            if signals[t] == -1 and holdings>0:
                proceeds = holdings*price[t]*(1-fee)
                cash += proceeds; holdings = 0
            record(cash, holdings, total=cash+holdings*price[t])
        return records
```

After backtesting, the pipeline computes Return on Investment,

$$
\mathrm{ROI} = \frac{\text{Final Portfolio} - \text{Initial Capital}}{\text{Initial Capital}},
$$

and the daily Sharpe Ratio,

$$
\mathrm{SR} = \frac{E[r_t]-r_f}{\sigma[r_t]},
$$

where $r_f$ is the risk-free rate and is often set to zero for crypto [2206.14932]. 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` [2206.14932]. 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 $T$, and `ExecutionManager` sends orders through a broker API [2206.14932]. 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` [2206.14932].

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 [2206.14932].

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 [2206.14932]. 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 [2403.18124] and for the “Search for Transient Objects in New detections using Known Sources” in XMM-Newton transient astronomy [2405.13630], including subsequent observational applications and operational descriptions [2601.19328; 2511.17385]. In the context of algorithmic trading, however, STONKS refers specifically to the seven-stage data science pipeline described above [2206.14932].

Source: https://www.emergentmind.com/topics/stonks-pipeline