TradingView strategy research

Statistical arbitrage research: baskets, neutrality and model failure

Statistical arbitrage uses a statistical model to trade relative mispricing across assets. In a residual mean-reversion approach, researchers remove estimated common-factor returns, score the remaining deviations, then build a constrained long/short basket. The expected convergence is uncertain: dollar neutrality does not remove factor risk, execution costs can exceed the signal, and the fitted relationship can fail. A TradingView monitor can display observations; validating a basket requires separate accounting for every holding and trade.

See the decision guide

From common factors to residual signals

Avellaneda and Lee study U.S. equity statistical arbitrage using principal components and sector ETFs to model common returns, then examine mean reversion in residual processes. That research motivates a multi-asset workflow; it does not establish an edge for the illustrative basket on this page. Pairs trading is a two-asset relative-value case. A larger book also needs rules for overlapping signals, shared factor exposures and scarce short inventory.

  • Define a return model r(i,t) = alpha(i) + sum over k of beta(i,k) × f(k,t) + epsilon(i,t). Fit coefficients using only earlier data. The residual epsilon is the return left unexplained by that particular model; it is not automatically a pricing error.
  • Choose the state being tested for reversion. For example, accumulate daily residual returns into X(i,t) using a declared reset date, then estimate its reference mean and deviation in training. A one-day residual return and a cumulative residual state are different signals.
  • For the chosen state, z(i,t) = (X(i,t) - mu(i)) / sigma(i), with sigma(i) > 0. Large positive z can suggest a short candidate and negative z a long candidate under the reversion hypothesis. A z-score alone neither proves stationarity nor gives a reliable Gaussian tail probability.
  • PCA loadings, factor count, sector classifications and residual scaling all belong to the model specification. Keep historical universe membership and delisted assets where the test requires them; selecting only current survivors changes the question.

Constrain basket weights before sizing orders

Let w(i) be signed dollar exposure divided by a chosen gross-notional budget N. Positive weights are long and negative weights are short. With sum |w(i)| = 1, N is gross exposure, not account equity or available margin. Convert to shares using q(i) = N × w(i) / P(i) for same-currency cash equities, then recheck the constraints after lot rounding.

  • One possible construction minimizes squared distance from raw signal weights, plus a penalty for changes from current weights, subject to these constraints. Record the objective and all limits. Simply clipping individual weights can break neutrality.
  • If the constraints are infeasible, skip the rebalance or reduce the gross budget under a predeclared rule. Do not silently relax factor limits until the desired trade fits. Removing an unavailable short requires solving the remaining basket again.
ConstraintEquation or ruleWhat remains exposed
Dollar neutralitysum w(i) = 0Equal long and short dollars can still have different market betas.
Factor neutralityFor each selected factor k: sum w(i) × beta(i,k) = 0Estimated loadings can drift; unmodeled factors remain.
Concentration|w(i)| ≤ a declared name limit; sector totals within limitsCorrelated residuals and common exits can still concentrate losses.
Trading and borrow|trade dollars(i)| ≤ participation cap × dollar ADV(i); confirmed short availabilityAverage volume does not guarantee executable depth or continuing borrow.

Four assets: exact neutrality and a dollar P&L check

These fictional USD equities use N = $100,000 of gross exposure. The weights are an arithmetic example, not fitted signal recommendations. Assume the displayed prices are executable for this calculation and the estimated market betas are fixed. All positions use one dollar of value per share per dollar of price change.

  • Initial net weight is 0.30 + 0.20 - 0.20 - 0.30 = 0. Initial market-beta exposure is 0.30 × 1.2 + 0.20 × 0.8 - 0.20 × 1.1 - 0.30 × 1.0 = 0. This checks only the stated market factor, not sector neutrality.
  • Gross P&L is sum q(i) × (Pnext(i) - Pentry(i)) = $850, or 0.85% of initial gross exposure. This is not an equity return. Capital, collateral and financing must be specified before reporting an account return.
  • After the move, long value is $50,800 and short value is $49,950. Gross exposure is $100,750 and net long exposure is $850. With unchanged beta estimates, dollar beta exposure is $950. Initially neutral quantities do not stay neutral as prices move.
  • An alternative failure scenario has A and B each fall 2% while C and D each rise 2%. The same quantities lose $2,000 before costs, despite their initial dollar and estimated market-beta neutrality.
AssetWeight / market betaEntry price / signed sharesNext price / gross P&L
A+0.30 / 1.2$50 / +600$51 / +$600
B+0.20 / 0.8$100 / +200$101 / +$200
C-0.20 / 1.1$40 / -500$39.60 / +$200
D-0.30 / 1.0$60 / -500$60.30 / -$150

Rebalancing has its own trade ledger

For a separate rebalance branch after the first price move, keep the gross target fixed at $100,000 and restore the original dollar allocations. Signed target minus signed current value gives the required trades: sell $600 of A, sell $200 of B, short another $200 of C and buy back $150 of D. Absolute traded notional is $1,150. This illustration permits fractional shares; actual lots change the residual exposures.

  • One-way traded-notional ratio is $1,150 / $100,000 = 1.15%. Some reports divide the sum of absolute weight changes by two and call that turnover; state the convention rather than comparing unlike numbers.
  • At an illustrative all-in execution allowance of 5 basis points per traded dollar, this rebalance costs $0.575. That linear allowance is a scenario, not a market-impact model. Execution costs usually need stress tests as order size increases.
  • In the alternative branch that liquidates every position instead of rebalancing, entry plus exit traded notional is $100,000 + $100,750. At the same 5 bp allowance, execution costs are $100.375 and the $850 gain becomes $749.625 before borrow, financing, distributions and taxes. Do not charge both branches to the same path.
  • Use actual per-leg fills and cash flows in a full simulation. Short borrow is charged under the broker fee base and day-count convention; short dividend obligations, long dividends, currency conversion and debit financing need separate entries. If fill prices already include slippage, do not deduct it again.

Freeze training and declare the rebalance clock

An illustrative experiment uses 252 synchronized daily observations for training followed by 63 untouched observations for evaluation. The dates, model, costs and limits must be chosen before inspecting the later results. These sample sizes are bookkeeping examples, not evidence of statistical adequacy.

  • Do not recompute historical residuals using a final full-sample PCA basis and call them contemporaneous signals. Estimating the risk model on the entire evaluation period leaks information even when order rules use only past bars.
  • Define what happens to missing prices, holidays and incompatible sessions before testing. Forward-filling a halted asset can manufacture a small residual or a false convergence. A missing mark does not eliminate an existing position.
  • Predeclare exits for convergence, maximum holding time, portfolio loss and operational failure. A statistical threshold is a decision trigger, not a guaranteed exit price. Margin and unmatched-leg exposure can force action before a signal reverses.
StageRequired record
Training boundaryHistorical universe, price adjustments, factor definitions, coefficients, residual initialization, normalization, selection tests and every candidate tried.
Frozen evaluationUse the saved factor loadings and normalization. Compute observations only when all required closes are available; submit orders for later executable prices.
Scheduled decisionsFor example, review targets at each completed daily close. Trade only when a declared exposure or target-change threshold is breached; retain every skipped and rejected order.
Refit boundaryFit the next model only with data then available. Either liquidate under a declared policy or trade from actual old holdings to new targets. Record those costs.
Final reportCombine marked open holdings, cash flows, failed fills and costs. Preserve all folds and failed models, including the final untouched period.

The smallest leg can set basket capacity

A simple entry-capacity screen limits each new order to 1% of its trailing average daily dollar volume (ADV). Suppose A, B, C and D have hypothetical dollar ADVs of $1,000,000, $2,000,000, $500,000 and $800,000. For entry from flat, the gross budget must satisfy N ≤ min over nonzero weights of (0.01 × ADV(i) / |w(i)|).

  • The four limits are about $33,333, $100,000, $25,000 and $26,667. C therefore caps this simplified basket at $25,000 gross. At the $100,000 illustrative size above, its $20,000 short entry would consume 4% of ADV and fail the 1% screen.
  • Apply the participation test to actual rebalance orders rather than the full holding each day. A reversal can require substantially more trading than a small weight adjustment. Missing or zero ADV makes a required trade ineligible under this screen.
  • This bound ignores spread, intraday depth, borrow inventory, crowding and forced-exit liquidity. Lower available borrow or a tighter margin constraint can reduce capacity further. The 1% threshold is an assumption, not a safe execution guarantee.

Observe a fixed four-asset basket in Pine

This monitor displays M(t) = sum w(i) × (P(i,t) / Preference(i) - 1). With shares fixed at q(i) = N × w(i) / Preference(i), N × M(t) equals the marked price-change P&L before costs and cash flows. Enter reference prices from a common timestamp and keep them fixed. This is an accounting check, not the residual model, a rebalanced portfolio, or a signal generator. The default ETF symbols and reference prices are placeholders, not a calibrated trade.

  • Use standard candles, compatible USD feeds and consistent adjustment policies. The chart must share the requested daily session boundaries. The monitor leaves missing or misaligned bars blank; timestamp equality cannot prove feed quality or executable prices.
  • For the fictional next prices 51, 101, 39.60 and 60.30 with references 50, 100, 40 and 60, the plotted calculation is 0.85%. At the reference prices it is zero. Changing a reference input redraws history, so save the inputs with the original research record.
  • TradingView request.security retrieves observations from other symbols; it does not open positions in them. Strategy orders use the chart broker emulator. A single-chart report cannot supply independent fills, borrow and margin accounting for this basket.
Pine Script v6 indicator. Four fixed allocations, no orders or fitting. Syntax validation does not validate data alignment, execution or expected profitability.pine
//@version=6
indicator("Fixed four-asset basket monitor", overlay = false)
string a = input.symbol("AMEX:SPY", "Asset A")
string b = input.symbol("NASDAQ:QQQ", "Asset B")
string c = input.symbol("AMEX:IWM", "Asset C")
string d = input.symbol("AMEX:DIA", "Asset D")
float pa = input.float(50.0, "A reference price", minval = 0.000001)
float pb = input.float(100.0, "B reference price", minval = 0.000001)
float pc = input.float(40.0, "C reference price", minval = 0.000001)
float pd = input.float(60.0, "D reference price", minval = 0.000001)
int start = input.time(timestamp("01 Jan 2026 00:00 +0000"), "Reference timestamp")
if not timeframe.isdaily or timeframe.multiplier != 1
    runtime.error("Use standard one-day candles with matching sessions.")
[ca, ta, ea] = request.security(a, "1D", [close, time, time_close], gaps = barmerge.gaps_on, lookahead = barmerge.lookahead_off)
[cb, tb, eb] = request.security(b, "1D", [close, time, time_close], gaps = barmerge.gaps_on, lookahead = barmerge.lookahead_off)
[cc, tc, ec] = request.security(c, "1D", [close, time, time_close], gaps = barmerge.gaps_on, lookahead = barmerge.lookahead_off)
[cd, td, ed] = request.security(d, "1D", [close, time, time_close], gaps = barmerge.gaps_on, lookahead = barmerge.lookahead_off)
bool prices = not na(ca) and not na(cb) and not na(cc) and not na(cd) and ca > 0 and cb > 0 and cc > 0 and cd > 0
bool aligned = ta == time and tb == time and tc == time and td == time and ea == time_close and eb == time_close and ec == time_close and ed == time_close
bool ready = prices and aligned and barstate.isconfirmed and time_close >= start
float mark = ready ? 0.30 * (ca / pa - 1) + 0.20 * (cb / pb - 1) - 0.20 * (cc / pc - 1) - 0.30 * (cd / pd - 1) : na
plot(100 * mark, "Price-change P&L / initial gross (%)", color = color.blue, linewidth = 2, style = plot.style_linebr)
hline(0, "Zero price-change P&L", color = color.gray)

Treat drift as a reason to suspend and investigate

A residual becoming extreme can mean that the model has broken. Monitor realized residual variance, convergence time, factor exposures after rounding, borrow changes and slippage against the assumptions saved at the training boundary. Define review limits before looking at losses; a refit should not erase a failed model from the record.

  • If residual variance doubles while sigma remains frozen, z-scores become more frequent even with no improvement in opportunity. Silently increasing sigma makes historical signals incomparable.
  • If all shorts become expensive to borrow or many baskets exit together, the liquidity model can fail while the price model still looks plausible. Stress simultaneous exits and partial fills; preserve the cost of unwinding unmatched legs.
  • Compare net results across untouched periods, neighboring parameter choices and larger execution-cost assumptions. Report the number of models tried. A good final chart after many unreported trials is weak evidence.
  • Use Pine Script AI Coding Agent to draft observable calculations and request syntax checks. Strategy Optimizer can compare supported inputs of a separate TradingView strategy; it cannot optimize this indicator as a portfolio backtest or establish multi-asset capacity. Keep basket fitting and the execution ledger in an external research environment.
Where Pineify fits

Pine Script AI Coding Agent

Turn explicit basket observations into a Pine indicator, request a syntax check and review missing-data behavior. Keep factor estimation and multi-asset execution accounting separate.

Also useful: Strategy Optimizer. Compare input combinations for a supported TradingView strategy after its timing and cost assumptions are checked. The four-asset indicator above has no strategy orders or portfolio backtest to optimize.

Draft a basket monitor

Frequently asked questions

Educational research, not investment advice. The assets, returns, weights, costs and volume figures in the worked examples are hypothetical. No performance run or profitable strategy is claimed. Statistical models and neutral exposures do not prevent losses.

Sources and verification

Published by Pineify. Pineify is an independent product and is not affiliated with TradingView. Sources support the technical explanations; examples do not establish trading performance.