Skip to content
Applied engineeringPrototype

Verace Parity

A statistical-arbitrage pairs-trading engine combining cointegration, Ornstein-Uhlenbeck z-score barriers and drawdown-constrained position sizing.

Verace Research
  1. Cointegrated spread: Hedged combination of two prices that reverts to its mean
  2. Spread z-score: Spread standardised by its OU mean and volatility
  3. Spread entry: Opens a long or short spread position
  4. Entry barrier at 2.5: Symmetric barrier the z-score must cross
Figure 1. Z-score barriers on a cointegrated spread in Verace Parity. Schematic with a synthetic series: a cointegrated spread standardised to a z-score, with symmetric barriers that turn it into entry, take-profit and stop decisions. Verace Parity is a prototype with results only from backtests.
Open the simulator on its own pageA rule reading a series: an interactive toy model of the principle. You can also try it below

Overview

Verace Parity is the lab's statistical-arbitrage system for pairs and basket trading under hard drawdown rules. It asks whether a portfolio of cointegrated instruments can be traded inside a fixed loss envelope: a daily-loss cap, a trailing-drawdown cap near 4 to 5%, and a profit target of 8%. Two assets are cointegrated when a linear combination of their prices is stationary even though each price wanders. Verace Parity takes that combination, called the spread, and acts on it only when it sits far from its long-run mean.

Every part of the system follows one pipeline. A hedge ratio is estimated to form the spread. The spread is fitted as an Ornstein-Uhlenbeck (OU) process dSt=θ(μ−St)dt+σdWtdS_t = \theta(\mu - S_t)dt + \sigma dW_t, a continuous-time mean-reverting model. The spread is then standardised to a z-score, and symmetric barriers turn it into entry, take-profit and stop decisions. A risk layer sizes each position and halts on drawdown. Two parts implement this pipeline. The first is a pairwise research implementation. The second extends it with Johansen basket cointegration, an order-flow shock filter, a drawdown-barrier sizer and a C++ multi-account mirror.

Both parts are Python packages with a web API, a WebSocket telemetry stream, a browser dashboard and a command-line tool. The second part adds C++ headers. The lab's records report a walk-forward backtest over 500 bars with a return of +9.92%, maximum drawdown of -1.34%, Sharpe ratio 3.84 and Sortino ratio 6.12. In the first part, the backtest entry points run on synthetic preset pairs. The technical reference states a 92.4% win rate and a 0.24 ms mirror latency. Several records do not support those figures, as the findings explain.

Status: the strategy pipeline, risk layer, backtesters and dashboards are implemented, and the documentation reports test suites passing 6 of 6 and 5 of 5. Order execution is implemented as broker connectors that fall back to simulated results when no terminal is present. The system is configured for 15 accounts, and nothing shows that any such accounts exist. Nothing shows whether any connector reached a live or test account. The only recorded performance figures come from backtests, mostly on synthetic data. Out-of-sample evaluation on real data, with costs, is not recorded.

Status

Prototype. Both parts contain working code with unit tests and backtesters, but the only recorded results are a single walk-forward figure set and documentation claims, mostly on synthetic data.

Simulator

A made-up series, and a rule that fires when a point lies far from the average of the points before it. Set how far, and how many points it looks back over.

  • synthetic data: not a record of any market
  • score: distance from the average, in units of the spread
Times the rule fired
21
Points outside the band
27%
Longest stretch without firing
43 points
The series
Synthetic

Narrow the band and the rule fires on noise; widen it and it misses moves. A longer window makes the band slower to follow.

This simulator is an illustration of the principle, with made-up numbers. It does not run the lab's code or show the lab's data, and nothing in it is a measurement.

Architecture

  1. Cointegration engine

    Estimates the OLS hedge ratio between two instruments, forms the residual spread and runs a simplified Dickey-Fuller stationarity test to decide whether a pair is tradeable.

  2. Ornstein-Uhlenbeck engine

    Fits the OU process to a spread series and returns its mean, reversion speed, equilibrium volatility and half-life. It also gives a verdict on whether the spread reverts fast enough to trade.

  3. Barrier filter

    Maps the spread z-score and the current position to one action: long spread, short spread, close for profit, close at stop, or hold. It also returns a confidence value and a reason.

  4. Risk guardian

    Tracks equity and peak equity, sizes lots by fixed risk percentage, and enforces hard daily-loss and trailing-drawdown halts. It also tracks a two-phase evaluation status.

  5. Walk-forward backtester

    Re-estimates the hedge ratio and OU parameters on a rolling window at every bar, applies the barrier rules, and reports PnL, drawdown, Sharpe, Sortino and a pass flag.

  6. Johansen VECM engine

    In the second part, solves the Johansen reduced-rank problem across a basket of up to five instruments and returns stationary basket weights. VECM stands for vector error-correction model.

  7. Order-flow shock blocker

    Computes a standardised order-flow imbalance from the top of the order book. It freezes new entries when that imbalance signals an abrupt move.

  8. Drawdown barrier sizer

    Scales a Merton-style allocation fraction toward zero as trailing drawdown approaches its hard cap. The Python and C++ versions of this sizer differ in detail.

  9. Multi-account mirror

    Replicates one signal across a configured list of accounts, sizes each by its own drawdown state, and skips accounts whose breakers have tripped. It is implemented in Python and as a C++ header with an OpenMP parallel loop.

  10. Real-data backtester

    In the second part, runs paired and basket backtests on downloaded market data, which is cached as CSV, with transaction costs and leverage.

  11. Broker connectors

    Execution bridges for a broker terminal package and a cloud order-routing service. Each returns simulated balances and order tickets when no terminal or token is available.

  12. API, dashboard and CLI

    A FastAPI service exposes health, telemetry, toggle, backtest and order endpoints, plus a WebSocket stream. A browser dashboard charts the z-score against its barrier bands, and a command-line tool exposes scan, backtest and trading-loop commands.

Implementation

Mechanisms as they are implemented in the source code, with the constants the code uses.

Rolling hedge ratio and spread z-score
At each bar tt the first part's backtester fits β\beta and α\alpha by OLS on the window [t−L,t)[t-L, t). It then fits the OU parameters on the resulting spread and sets zt=(At−βBt−α−μ)/σeqz_t = (A_t - \beta B_t - \alpha - \mu)/\sigma_{eq}. The second part's real-data backtester instead uses β=cov(a,b)/var(b)\beta = \mathrm{cov}(a,b)/\mathrm{var}(b) over a 150-bar window and standardises by the window mean and standard deviation.
Simplified Dickey-Fuller test
After the OLS step A=α+βBA = \alpha + \beta B, the residual spread is regressed as ΔSt=c+γSt−1\Delta S_t = c + \gamma S_{t-1} with a single lag. The t-statistic is compared with fixed critical values of -3.46, -2.88 and -2.57 at the 1%, 5% and 10% levels, set for samples of about 200, and p-values follow a step function. The technical reference calls this an augmented Dickey-Fuller test, but the code uses no augmentation lags.
OU exact-discretisation calibration
The spread is regressed as St+1=aSt+bS_{t+1} = a S_t + b by OLS, with residual variance η2\eta^2 clamped at 1e-12 or higher. The code then sets θ=−ln⁡(a)/Δt\theta = -\ln(a)/\Delta t, μ=b/(1−a)\mu = b/(1-a), σ=2θη2/(1−a2)\sigma = \sqrt{2\theta\eta^2/(1-a^2)}, t1/2=ln⁡2/θt_{1/2} = \ln 2/\theta and σeq=σ/2θ\sigma_{eq} = \sigma/\sqrt{2\theta}. It needs at least 10 observations; the degenerate fallback sets θ=0.01\theta = 0.01 and a half-life of 69.3.
Mean-reversion gate
The OU engine labels a spread tradeable when its half-life lies between 1 and 120 bars and θ>0.005\theta > 0.005. The configuration applies a stricter screen: lookback of 200 bars, rejection of pairs with half-life above 80 bars, and a Dickey-Fuller p-value of at most 0.01.
Three-barrier z-score state machine
The system opens a long spread position when z≤−2.5z \le -2.5 and a short spread position when z≥2.5z \ge 2.5. It takes profit when ∣z∣≤0.15|z| \le 0.15 and stops out when ∣z∣≥3.8|z| \ge 3.8 in the adverse direction. Long-spread PnL is PnLA−β PnLB\mathrm{PnL}_A - \beta\,\mathrm{PnL}_B. The same constants appear in both Python parts, in the C++ filter header and in the API request schema defaults.
Fixed-fractional lot sizing
Risk capital is the balance times max_risk_per_trade_pct divided by 100, with 0.5% as the example value. This is divided by stop distance times point value (default 10) to give lots, which are clamped to the range 0.01 to 20. In the backtester the stop distance is ∣zstop−z∣ σeq|z_{stop} - z|\,\sigma_{eq} with a minimum of 5e-4. The technical reference describes ATR-based sizing, which the code does not implement.
Drawdown circuit breaker
Trading halts when (Eday−E)/Eday(E_{day} - E)/E_{day} reaches the daily-loss limit or (Epeak−E)/Epeak(E_{peak} - E)/E_{peak} reaches the total-loss limit, with example limits of 3.5% and 4.5%. A daily halt clears at day rollover, while a trailing-drawdown halt stays in place.
Walk-forward PnL and pass rule
Per bar, position PnL is ±(ΔA⋅lots−ΔB⋅lots⋅β)⋅mult\pm(\Delta A \cdot \mathrm{lots} - \Delta B \cdot \mathrm{lots} \cdot \beta) \cdot \mathrm{mult}. In the first part a run passes when profit is at least 8% and maximum drawdown is at most 4.5%. The second part's real-data backtester uses 8% and 4.2%.
Synthetic cointegrated pair generator
Leg B follows a geometric random walk. The spread is a discrete OU step ds=−θs+σεds = -\theta s + \sigma\varepsilon with defaults θ=0.08\theta = 0.08 and σ=0.0012\sigma = 0.0012, and leg A is βPb\beta P_b (with β=0.85\beta = 0.85) plus the spread plus N(0,0.0004)N(0, 0.0004) noise. Presets set β\beta, θ\theta and σ\sigma per pair, and the trading-loop simulator uses ds=−0.06s+0.0006 εds = -0.06 s + 0.0006\,\varepsilon with leg B returns drawn from N(10−5,8×10−4)N(10^{-5}, 8 \times 10^{-4}).
Johansen reduced-rank cointegration
R0R_0 and R1R_1 are the residuals of ΔY\Delta Y and Yt−1Y_{t-1} on lagged differences, used raw when there is one lag, and Sij=Ri⊤Rj/TS_{ij} = R_i^\top R_j / T. The generalised eigenproblem S10S00−1S01v=λS11vS_{10} S_{00}^{-1} S_{01} v = \lambda S_{11} v is solved with scipy.linalg.eig and the eigenvalues are sorted in descending order. The top eigenvector, normalised to the first asset, gives the stationary basket weights.
Moment-based OU speed estimate
The second part estimates θ=−∑Δst(st−1−sˉ)/∑(st−1−sˉ)2\theta = -\sum \Delta s_t (s_{t-1} - \bar s) / \sum (s_{t-1} - \bar s)^2, clipped to [0.005,0.95][0.005, 0.95], with half-life ln⁡2/θ\ln 2/\theta in bars. The code labels the half-life in minutes, but its true unit depends on the bar size.
Order-flow imbalance blocker
Following the Cont-Kukanov-Stoikov definition, ete_t is the bid term minus the ask term. The bid term contributes the new size if the bid rose, the size change if it was unchanged, and minus the previous size if it fell; the ask term mirrors this. The series is standardised, and new entries are frozen when ∣zOFI∣≥3.0|z_{OFI}| \ge 3.0 and no position is open.
Drawdown-barrier allocation fraction
The fraction is f∗=fM[1−e−100κ(DDmax−DDt)]f^* = f_M [1 - e^{-100\kappa (DD_{max} - DD_t)}] with fM=(μ−r)/(γσ2)f_M = (\mu - r)/(\gamma \sigma^2), where the slack DDmax−DDtDD_{max} - DD_t is a fraction, DDmaxDD_{max} is 4.2%, γ=2.0\gamma = 2.0, κ=1.5\kappa = 1.5 and r=0.045r = 0.045. The C++ header multiplies the fractional slack by 100 inside the exponent and clamps the result to [0,0.15][0, 0.15]. The Python sizer scales the Merton fraction by 0.005, caps it at 12% and uses the slack expressed in percent, which applies the same factor of 100. The code calls this an HJB (Hamilton-Jacobi-Bellman) controller, but it solves no partial differential equation.
Per-account mirror fan-out
One signal is replicated over all configured accounts. Each account is sized by its own drawdown-dependent fraction and skipped when its drawdown or daily-loss breaker has tripped, with a 4.20% drawdown halt. The asynchronous version uses asyncio.gather over non-halted accounts, and each dispatch is simulated as a 1 ms sleep returning FILLED with a fixed 1.2 ms latency.
C++ fan-out benchmark
master_bot.cpp passes a fixed signal of z=−2.85z = -2.85 through OUJumpFilter and the configured account mirror 1000 times and prints the mean fan-out latency. The mirror loops over accounts with an OpenMP parallel-for.
Real-data backtest settings
Paired backtests on downloaded 15-minute and daily data use rolling OLS spread z-scores with drawdown-barrier sizing, a cost of 1 basis point and 10x leverage. The macro basket backtest applies a fixed per-trade gain instead of simulating price moves.
Correlated synthetic order-book feed
Independent N(0,0.0008)N(0, 0.0008) shocks are multiplied by the transposed Cholesky factor of a fixed correlation matrix, with equity-index correlations of 0.84 to 0.94 and yield correlations of -0.5 to -0.65. Prices compound as pt=pt−1(1+et)p_t = p_{t-1}(1 + e_t) across five instruments, and a toy order book drives the telemetry endpoints. The trading loop's own tick generator uses ds=−0.08s+0.0008 εds = -0.08 s + 0.0008\,\varepsilon.
Broker connector with simulation fallback
When the broker terminal package is unavailable or unconnected, every connector method returns simulated account data and random order tickets, so the system runs without a broker. The cloud bridge sends market orders only when an access-token environment variable is set and otherwise returns a message that a bridge is required. One further connector is a stub.

Results

From the lab's own experiments and records. They have not been independently replicated.

  1. Walk-forward backtest over 500 bars

    The lab's records report a return of +9.92%, maximum drawdown of -1.34%, Sharpe ratio 3.84 and Sortino ratio 6.12, with the pass criterion met. The first part's backtest entry points generate synthetic preset pairs, so this result does not establish performance on market data.

  2. Stated win rate has no recorded run

    The technical reference of both parts states a 92.4% win rate for the 2.5 sigma barrier. No record shows the experiment, data or trade count behind that figure.

  3. Mirror latency figure measures a fixed signal

    The technical reference states a 0.24 ms fan-out latency. The C++ benchmark that measures fan-out repeats a fixed z=−2.85z = -2.85 signal 1000 times through an in-memory mirror, and the Python asynchronous mirror reports a fixed simulated 1.2 ms latency, so neither figure measures order execution.

  4. Command-line backtest prints hardcoded figures

    The test suite and code show that the second part's command-line backtest command prints fixed numbers without simulating anything.

  5. Macro basket backtest assumes a fixed gain

    The second part's real-data backtester applies a fixed per-trade gain in its Johansen basket mode, so that mode's results reflect the assumption rather than market data.

  6. Documentation and code disagree in several places

    The technical reference describes an augmented Dickey-Fuller test, exact maximum-likelihood OU fitting, ATR lot sizing and a basket half-life target under 12 minutes. The code uses a single-lag Dickey-Fuller regression with step-function p-values, an OLS AR(1) fit and fixed-fractional sizing, and measures half-life in bars.

  7. HJB controller is a closed-form heuristic

    The drawdown sizer is named after the Hamilton-Jacobi-Bellman equation, but the code computes a Merton fraction times an exponential barrier and solves no control problem. Its Python and C++ versions differ in scaling and caps.

  8. Unit tests pass in both parts

    The documentation reports 6 of 6 tests passing in the first part and 5 of 5 in the second. The tests cover cointegration, OU fitting, barrier signals, risk limits, the Johansen solver, the order-flow blocker and the multi-account manager.

Concepts

Cointegration
Two or more non-stationary price series are cointegrated when some linear combination of them is stationary. That combination is the spread the system trades.
Hedge ratio
The coefficient β\beta in S=A−βB−αS = A - \beta B - \alpha that makes the spread stationary. The system estimates it by OLS on a rolling window.
Ornstein-Uhlenbeck process
A continuous-time mean-reverting stochastic process, dSt=θ(μ−St)dt+σdWtdS_t = \theta(\mu - S_t)dt + \sigma dW_t. Here θ\theta sets the speed of reversion toward the mean μ\mu.
Half-life of mean reversion
The expected time for a deviation from the mean to halve, ln⁡2/θ\ln 2/\theta. The system uses it to reject spreads that revert too slowly.
Equilibrium volatility
The stationary standard deviation of the OU process, σ/2θ\sigma/\sqrt{2\theta}. The system uses it to standardise the spread into a z-score.
Dickey-Fuller test
A unit-root test that regresses the change of a series on its lagged level. A strongly negative t-statistic indicates stationarity.
Johansen procedure
A multivariate cointegration method that finds stationary combinations of several series from a generalised eigenvalue problem on residual moment matrices.
Barrier rule
A decision rule with fixed thresholds on the z-score: enter at 2.5, take profit within 0.15 of zero, stop at 3.8.
Order-flow imbalance
A signed measure of net buying or selling pressure computed from changes in the best bid and ask prices and sizes. The second part uses it to detect abrupt moves.
Merton fraction
The allocation (μ−r)/(γσ2)(\mu - r)/(\gamma \sigma^2) for an asset with excess return μ−r\mu - r, volatility σ\sigma and risk aversion γ\gamma. The second part uses it as the base size before applying the drawdown barrier.
Drawdown barrier
A multiplicative gate 1−e−100κ slack1 - e^{-100\kappa\,\mathrm{slack}}, where slack is the remaining distance between trailing drawdown and its hard cap written as a fraction, that shrinks position size to zero as trailing drawdown approaches the cap.
Trailing drawdown
The fall of equity from its running peak, as a fraction of that peak. Both parts use it as a hard halt condition.
Walk-forward backtest
A backtest that re-estimates all model parameters at each step using only past data, so that no future information enters a decision.
Two-phase evaluation rule
The pass criterion that both backtesters encode: a profit target of 8% reached without breaching a drawdown cap of 4.5% in the first part or 4.2% in the second.
Simulation fallback
A design in which every execution connector returns simulated results when no broker connection is present, so the whole system runs offline.

About this page

Written from the lab's own documents and source code. Figures and results are the lab's measurements as it recorded them at the time, and have not been independently replicated.

Market results here are backtests and logs kept by the lab. Nothing on this page is financial advice.

Published under the PolyForm Noncommercial License 1.0.0: free for noncommercial use.