I'm trying to create a running median function in pine-script.
The purpose is to calculate a median error between an estimated ticker value and the actual ticker value.
See Plotting manual levels for daily high,low,close for a bit of history on this estimation.
For each new estimation, the median error will change over time, because it has to take into account all historical errors to find the median error.
To calculate a median we have to use the percentile_nearest_rank(source, length, percentage)
function with percentage=50
.
For example, percentile_nearest_rank(close, 100, 50)
will give the median of the last 100 close prices.
This will calculate the median of a sliding window of 100 bars back.
However, that's not what I'm looking for.
What I'd like to do is calculate the median between a fixed starting bar (fixed bar number or date) and the current bar.
Say that we have daily bars and my starting date is March 05.
On March 06, I have a length of 2 bars for my median calculation: percentile_nearest_rank(close, 2, 50)
On March 07, I have a length of 3 bars for my median calculation: percentile_nearest_rank(close, 3, 50)
On March 08, I have a length of 4 bars for my median calculation: percentile_nearest_rank(close, 4, 50)
etc...
This means that the length
parameter will increase on each bar.
So, I'm wondering if it's possible in pine script to use the percentile_nearest_rank
function where the length
parameter is not fixed, but changes on each bar.
If not, I'm open to alternatives if there are any.