TradingView Backtesting

Spearman Correlation for Trading Signals: Ranks, Ties and Returns

Spearman rank correlation measures whether higher signal values tend to accompany higher subsequent returns. Rank both columns within the same evaluation sample, assign average ranks to ties, then calculate Pearson correlation on those ranks. The result ranges from -1 to +1 when defined. It measures ordering, not the size of profits. A valid signal test also requires a return label that begins after the signal becomes available.

See the decision guide

Reproduce a six-observation ranking table

These invented observations represent one instrument at six eligible signal times. Each return uses the same later holding horizon; the numbers are arithmetic inputs, not measured strategy performance. Rank from smallest to largest. The two signal values of 2 occupy positions 2 and 3, so each receives rank 2.5. The two returns of 3% occupy positions 4 and 5, so each receives rank 4.5.

  • Both rank means are 3.5. The centered cross-product sum is 13.5; each centered squared-rank sum is 17. Spearman rho = 13.5 / sqrt(17 × 17) = 0.794118.
  • The association is positive, but observation D has a larger return than E and F despite its lower signal. The coefficient summarizes such ordering disagreements across the sample.
  • Pearson correlation on the original signal and return values is 0.855717. Changing returns from percentage points to decimal units leaves either coefficient unchanged.
ObservationSignal xLater return yRank xRank y
A1-2%11
B21%2.53
C20%2.52
D44%46
E53%54.5
F63%64.5

Use correlation of ranks when values tie

Let Rᵢ and Sᵢ be the average ranks of the retained signal and return observations. Compute rho = Σ[(Rᵢ - mean R)(Sᵢ - mean S)] / sqrt(Σ(Rᵢ - mean R)² × Σ(Sᵢ - mean S)²). This is Pearson correlation applied to ranks, as described in the R statistics documentation. The denominator must be nonzero.

  • The shortcut rho = 1 - 6Σdᵢ² / [n(n² - 1)], where dᵢ = Rᵢ - Sᵢ, assumes no ties in either column. In this table Σdᵢ² = 7. The shortcut gives 0.8, which differs from the correct tied-rank result of 0.794118.
  • In a spreadsheet with signal values in B2:B7 and returns in C2:C7, enter =RANK.AVG(B2,$B$2:$B$7,1) in D2 and =RANK.AVG(C2,$C$2:$C$7,1) in E2. Fill down, then use =CORREL(D2:D7,E2:E7). First prepare a table containing only complete numeric pairs.
  • Do not rank equal signals by row order. That invents distinctions the signal never made. Avoid rounding numeric values before ranking unless that rounding is part of the actual trading rule.

Pearson measures linear association; Spearman measures ordering

Pearson retains the numerical distance between values. Spearman replaces that distance with rank spacing. Choose the statistic for the research question, and inspect the underlying pairs before interpreting a difference between them.

  • A strictly increasing transformation preserves ranks and therefore Spearman correlation. Pearson can change under a nonlinear transformation. A strictly decreasing transformation reverses the rank direction.
  • Ranks limit the influence of an extreme value through its magnitude, but a bad observation can still alter ordering. Check data errors and examine a scatterplot of raw values as well as ranks.
  • Subtracting 10 percentage points from every return in the first table makes all six returns negative while leaving both correlations unchanged. Correlation alone cannot establish profitability, appropriate sizing or performance after trading costs.
Constructed inputsPearsonSpearmanInterpretation
x = 1, 2, 3, 4, 5; y = 1, 4, 9, 16, 250.9811051The nonlinear y = x² relationship is strictly increasing on these positive inputs.
x = -2, -1, 0, 1, 2; y = 4, 1, 0, 1, 400A U-shaped relationship can exist despite zero correlation by either measure.
The six-observation table above0.8557170.794118The larger raw-value association does not remove ordering errors.

Give each signal a genuinely later return label

Suppose s(t) becomes available after bar t closes. A research label r(t,h) = C(t+h) / C(t) - 1 measures the following h close-to-close intervals. Its endpoint is future information used only to evaluate s(t). It must never enter the signal, preprocessing or parameter selection available at time t.

  • A close-to-close label does not prove that an order based on the final close could fill at that same price. If the tested rule enters at the next open and exits at the close of its hth holding bar, use C(t+h) / O(t+1) - 1 and state the execution assumptions.
  • For h = 3 and eight closes C(1) through C(8), a signal at close 1 pairs with C(4) / C(1) - 1. Signals at closes 1 through 5 can have complete labels; signals at 6 through 8 cannot. Do not replace those unfinished labels with zero.
  • For that next-open convention, an illustrative O(t+1) of 100 and C(t+3) of 103 gives a gross return of 3%. Commission, spread and slippage require a separate execution calculation.
  • Keep timestamp, symbol, signal value, signal availability time, label start, label end and return in every row. Sorting each column independently before correlating destroys the pairing.
  • When splitting development and evaluation periods, remove development observations whose return labels extend into the evaluation period. Freeze the signal specification and horizon before examining later results.

Choose time-series or cross-sectional ranks explicitly

For a time-series test, rank one instrument across a declared interval. For a cross-sectional test, rank a declared universe at the same signal timestamp, then compare those ranks with returns over the same future interval. Pooling symbols and dates into one ranking can mix these two questions and introduce market or instrument differences into the result.

  • Record the instrument universe, price adjustments, timeframe, session, timezone, return horizon and signal version. A cross-sectional universe must reflect what was available at each date, including delisted instruments when relevant.
  • For cross-sectional analysis, calculate one coefficient per eligible date, record the number of instruments and tied values, then inspect the dated coefficients. An average across dates is a separate summary whose uncertainty depends on time dependence.
  • A full evaluation-window rank calculation is acceptable for an offline diagnostic. If the live signal itself uses a percentile or rank threshold, compute that input using only the history or contemporaneous universe available when trading.

Reject undefined inputs and distinguish sample size from evidence

A constant signal or constant return column has zero rank variance, so its correlation is undefined. Return an unavailable value with a reason, not zero. With only two distinct complete pairs, the coefficient is necessarily +1 or -1; that is arithmetic rather than persuasive evidence of a repeatable effect.

  • Remove a row if either member of the pair is missing or nonfinite, then rank the remaining pairs again. Record the original, excluded and retained counts. Missingness related to market stress can bias even a correctly calculated complete-pair result.
  • Small samples and many ties give coarse, unstable results. SciPy warns that its asymptotic Spearman p-value needs very large samples and suggests permutation testing for smaller samples. Permuting individual rows requires exchangeability under the chosen null; serially dependent trading data do not automatically meet that condition.
  • Adjacent five-bar forward returns share four return intervals. Their dependence can make a large row count misleading for inference. Compare non-overlapping labels, and use a time-series inference design that preserves relevant dependence if reporting uncertainty. Removing overlap alone does not prove independence.
  • Report sample dates, horizon, valid pair count, tie handling and coefficient with any uncertainty method. Track every signal and horizon tried. Choosing the largest correlation from many tests creates selection bias; retain a later evaluation period for the frozen choice.

Export the required series and keep the report boundary clear

TradingView chart CSV exports can include indicator values and the chart data that has loaded. Check the exported signal column, timestamps and history range before building forward returns. Strategy Report exports are separate: the List of Trades tab contains trades, while the Performance Summary contains metrics. Neither is a substitute for the complete signal-and-label table.

  • Pineify Backtest Deep Report parses trade timestamps, entry and exit prices, quantity and P&L, and calculates supported metrics such as net profit and profit factor. Its signalName field identifies a trade signal; it is not a numeric signal value recorded on every chart bar.
  • Use the report to reconcile trade records and outcomes. Calculate the Spearman statistic independently from the dated numeric series; this page does not claim that Backtest Deep Report includes this method.
  • Pine Script AI Coding Agent can help draft custom signal output from a written specification. Specify when the value becomes available and which series should be exported. Review the generated code and compare exported observations with a known example before analysis.
  • Rank Correlation Index describes the ordering of price against time inside a lookback window. Here the two variables are a signal and its subsequent return. RCI could be the signal under evaluation, but its own reading is not evidence of predictive rank correlation.
Where Pineify fits

Backtest Deep Report

Review supported metrics from your TradingView trade CSV and reconcile the trade outcomes before a separate signal-ranking analysis.

Also useful: Pine Script AI Coding Agent. Draft custom numeric signal output with explicit timing, then verify the exported series independently.

Review Backtest Deep Report

Frequently asked questions

Educational information, not investment advice. All numerical examples are constructed and do not represent measured trading performance. Correlation does not establish causation, executable profit or future returns.

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.