0

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.

Bjorn Mistiaen
  • 6,459
  • 3
  • 18
  • 42

2 Answers2

2

The computation of a rolling median using a window size of n data points will require an ordered list of these data points in an ascending order.

Since you want to use an increasing window size you would need to use a loop, however you can't sort within a loop (as far as i'am aware). So i think its not possible to do that.

You could use a cumulative mean cum(x)/bar_index as a replacement, i don't know if the difference would be significant in the case of closing prices.

alexgrover
  • 1,023
  • 1
  • 4
  • 6
0

The type of the length= parameter specified in the refman is not a series int, so no, it can't vary on each bar.

PineCoders-LucF
  • 8,288
  • 2
  • 12
  • 21