# Order-statistic Filters

Also known as: moving median, moving mode.
A Trend concept (Digital filters & smoothers) in the LuxAlgo Library, with 1 indicator implementation.

## What are Order-statistic Filters?

Order-statistic filters smooth a series by ranking rather than averaging. Slide a window of the last N values along the chart, sort the contents, and output the value at a chosen rank: the middle value gives the moving median, a chosen percentile gives a percentile filter, the two extremes give running maximum and minimum, and the most frequent value gives a moving mode. Because the output is chosen by rank, always an actual data point or an interpolation between two adjacent ones rather than a weighted blend of the whole window, these are nonlinear filters and behave differently from any moving average.

The family comes from signal processing and robust statistics. John Tukey proposed running-median smoothing in the early 1970s as part of exploratory data analysis, and median filters went on to become a staple of digital image processing because they remove salt-and-pepper noise while preserving edges. Traders inherited the tools directly: a bad tick is the chart's version of a corrupted pixel, and a genuine gap or regime break is an edge worth preserving. On modern platforms the general case is built in; Pine Script® provides median and percentile functions, and array support makes arbitrary ranks straightforward to compute.

The practical appeal is robustness. A single bad tick or one violent bar drags a mean in proportion to its size but barely moves a median, and where linear smoothers round off sharp level shifts, a median tends to preserve them, at the cost of a steppy, plateau-prone output. The family also generalizes familiar tools: Donchian channels are simply the 100th and 0th percentile filters plotted as a channel, and a median crossover system is a [moving average crossover](https://www.luxalgo.com/library/concept/moving-average-crossovers/) setup with means swapped for ranks.

## How to calculate a moving median

The moving median is the flagship order-statistic filter, and every other member of the family is the same procedure with a different rank.

1. Choose a window length N and, at each bar, collect the most recent N values of the source series (close, volume, an indicator, anything).
2. Sort the window's values in ascending order.
3. Output the middle value. With an odd N that is the single center element; with an even N, average the two center elements.
4. For the general case, output a different rank instead: the p-th percentile (interpolating between neighboring ranks where needed), the maximum, the minimum, or the most frequent value for a moving mode.

## How it's calculated

Filters that output a chosen rank of the last n prices rather than an average; the moving median is the best-known case.

```
W_t = (P_t, P_(t-1), ..., P_(t-n+1))
OSF_t = r-th smallest value in W_t
Median_t = value at rank (n + 1) / 2 in W_t, for odd n
Median_t = mean of the values at ranks n / 2 and n / 2 + 1, for even n
Mode_t = most frequent value in W_t, with prices rounded to bin width b

  P_t: source price at bar t (commonly close)
  t: bar index
  n: window length in bars (no universal default; odd lengths are typical)
  W_t: window of the last n prices at bar t
  r: selected rank, from 1 = smallest to n = largest
  OSF_t: order-statistic filter output at bar t
  Median_t: moving median at bar t, the rank (n + 1) / 2 order statistic
  Mode_t: moving mode at bar t
  b: bin width used to group nearly equal prices for the mode (no universal default)
```

Ranks r = 1 and r = n give the moving minimum and maximum; applied to the lows and highs these are the lower and upper Donchian channel lines.

A moving median follows clean step changes and ignores isolated spikes better than a mean of the same length, at the cost of a staircase-like output.

Exact price repeats are rare, so the moving mode is only meaningful on binned or rounded prices.

## How traders use it

- To despike raw data: a short moving median strips isolated bad ticks and single-bar anomalies before other indicators are computed, standard outlier handling.
- As a robust baseline: swapping a moving median in place of an [SMA](https://www.luxalgo.com/library/concept/sma/) or [EMA](https://www.luxalgo.com/library/concept/ema/) gives a centerline that one wide bar barely moves, useful in gappy or thinly traded markets.
- As percentile channels: an upper and lower percentile of price over a lookback frame a range that ignores the most extreme excursions, a softer alternative to pure high-low channels and a rank-based cousin of the [MA envelope](https://www.luxalgo.com/library/concept/ma-envelope/).
- Inside classic constructs: median-based variants of tools like [Supertrend](https://www.luxalgo.com/library/concept/supertrend/) or MACD replace the mean component so the signal reacts less to single-bar shocks.
- As a regime condition: price holding above a rising moving median, or the median's own slope, provides a robust [trend regime label](https://www.luxalgo.com/library/concept/trend-regime-label/), the same role an [MA slope filter](https://www.luxalgo.com/library/concept/ma-slope-filter/) plays but harder for one news bar to flip.

## Order-statistic Filters vs linear smoothers

- **SMA** (https://www.luxalgo.com/library/concept/sma/): An SMA is a linear filter: every value in the window contributes proportionally, so one outlier shifts the output. A moving median is rank-based, so an outlier's size never enters the output; at most it shifts which value sits in the middle.
- **EMA** (https://www.luxalgo.com/library/concept/ema/): An EMA weights recent data more heavily but is still linear, so a single extreme bar pulls it immediately and decays out of it slowly. A median never responds in proportion to an outlier's size, though the EMA tracks smooth turns more gracefully.
- **Ehlers SuperSmoother** (https://www.luxalgo.com/library/concept/ehlers-supersmoother/): The SuperSmoother is a carefully designed linear low-pass filter with little lag for its smoothness, but like all linear filters it rounds off level shifts and passes a scaled version of every spike. A median keeps step changes crisp and drops isolated spikes entirely, at the cost of plateau-shaped output.
- **VWMA** (https://www.luxalgo.com/library/concept/vwma/): A VWMA reweights the mean by volume, so it is still an average and still outlier-sensitive, just along a different dimension. Order-statistic filters discard magnitude altogether and keep only rank order.

## FAQ

### What is a moving median in trading?

It is the middle value of the last N bars, recomputed each bar: sort the window and take the center element (or the average of the two center elements when N is even). It smooths like a moving average of similar length but resists spikes: an extreme value lands at the end of the sorted window, so it can shift the median to a neighboring observation at most and never drags it in proportion to its size.

### When is a moving median better than a moving average?

When the data contains outliers: bad ticks, thin-market spikes, or one-bar news candles that would drag a mean. The median ignores them almost entirely. The trade-off is a steppier line that can sit still while price drifts, so neither is universally better; they suit different noise profiles.

### How long should a median filter window be?

Long enough to outvote the noise you want removed: a run of k consecutive spike bars survives unless the window holds at least 2k+1 values, so a 3-bar median only removes 1-bar spikes. Beyond that, the usual trade-off applies: longer windows are smoother and lag more.

### Is a moving median the same as a 50th percentile filter?

Yes. The median is the 50th percentile, so a percentile filter set to 50 reproduces it exactly, up to platform interpolation when the rank falls between two values. The percentile form is the general tool: shift the rank toward 100 or 0 and the output glides from median-like smoothing toward the running extremes.

### Do trading platforms have built-in median or percentile functions?

Most scripting environments do. Pine Script® exposes a median function plus percentile functions in nearest-rank and linear-interpolation variants, with equivalents in Python and other analysis stacks. Older scripts sometimes implement the sort manually with arrays, which is functionally the same filter.

### What is a moving mode and when is it useful?

It outputs the most frequent value in the window, usually after rounding prices into bins. It suits data where values genuinely repeat, such as the most-traded price of a session, and behaves erratically on continuous data without binning, which keeps it the least used member of the family.

## Implementations in the Library

- Percentile Nearest Rank Using Arrays (LuxAlgo): https://www.luxalgo.com/library/indicator/percentile-nearest-rank-using-arrays/

## Related concepts

- Gaussian Filter: https://www.luxalgo.com/library/concept/gaussian-filter/
- Butterworth Filter: https://www.luxalgo.com/library/concept/butterworth-filter/
- Chebyshev Filters: https://www.luxalgo.com/library/concept/chebyshev-filters/
- Elliptic Filter: https://www.luxalgo.com/library/concept/elliptic-filter/
- Bessel Filter: https://www.luxalgo.com/library/concept/bessel-filter/
- Ehlers SuperSmoother: https://www.luxalgo.com/library/concept/ehlers-supersmoother/
- Ehlers Instantaneous Trendline: https://www.luxalgo.com/library/concept/ehlers-instantaneous-trendline/
- Ultimate Smoother: https://www.luxalgo.com/library/concept/ultimate-smoother/
- Swiss Army Knife Filter: https://www.luxalgo.com/library/concept/swiss-army-knife-filter/
- Windowed FIR Smoothing: https://www.luxalgo.com/library/concept/windowed-fir-smoothing/

---

Source: https://www.luxalgo.com/library/concept/order-statistic-filters/ (LuxAlgo Library, the encyclopedia of trading & technical analysis). Free to use with attribution: https://www.luxalgo.com/library/license/