Rolling Median (MEDIAN)
Summary
The middle order statistic of the trailing window: the central value when optInTimePeriod is odd, the mean of the two central values when it is even. A robust measure of central tendency — unlike SMA, a single spike moves it by at most one rank however large the spike is, which is what makes it useful as a filter rather than as a level.
Not to be confused with MEDPRICE, which is (High + Low) / 2 of one bar and is not an order statistic.
Formula
With W the window sorted ascending and W[1] its smallest value:
n odd : MEDIAN = W[(n+1)/2]
n even: MEDIAN = ( W[n/2] + W[n/2 + 1] ) / 2
Notes
- This is not
PERCENTILEat 50.PERCENTILEreports the nearest rank, which at evennselects the lower of the two central values: on a 4-bar window of1, 2, 3, 4this function returns2.5andPERCENTILEreturns2. At oddnthe two agree bit for bit. - At even
nthe output can therefore be a value the series never traded at, which is the deliberate opposite ofPERCENTILE's design property. optInTimePeriodis not restricted to odd values: TA-Lib has no odd-only range mechanism, and it would surprise any caller reaching for a 20-bar median.- Every input value must be finite. A NaN makes every comparison against it false, which breaks the order the window is kept in, and the output can stay wrong long after the NaN has left the window.
Inputs
inReal— The series to take the median of
Outputs
outReal— Median of the trailing window
Parameters
| Parameter | Type | Default | Accepted values | Description |
|---|---|---|---|---|
optInTimePeriod | integer | 30 | 2–10000 | Number of trailing values in the window |
Properties
Numerical Stability: Start-Independent
| ✅ Overlap Input i |
| ☐ Independent Y-Axis |
| ☐ Candlestick |
| ☐ Can Output NaN or ±Inf |
| ☐ Identity at Period 1 |
Implementation
TA-Lib Definition: median.c · median.yaml
| Native | File |
|---|---|
| C | ta_MEDIAN.c |
| Rust | median.rs |
| Java | Core_MEDIAN.java |
| C# | Core_MEDIAN.cs |
TA-Lib is also available for Python, R and more using a wrapper.
Aliases
Rolling Median, Moving Median, Running Median
See Also
PERCENTILE · SMA · MEDPRICE
References
- NumPy
numpy.median, Rstats::median, scipy, ExcelMEDIAN— four independent implementations of one unambiguous definition.