Calculate change for each element in Pine Script array

1.2k Views Asked by At

I want to calculate the percent change between periods of each element in the "features" array (simply using the array as a grouping of financial time series data to report on). However the way the script is working now, it seems that it wants to calculate the percent change between each element in the array and not FOR each element in the array.

I don't think I've done anything wrong here in how I reference the array elements but I get the feeling there's some sort of 'under the hood' concept about how variables are processed by TV that is causing this issue.

//@version=4
study("My Script")

pct_change(source, period) =>
    now = source
    then = source[period]
    missing_now = na(now)
    missing_then = na(then)
    
    if not missing_now and not missing_then
        (now - then) / abs(then)
    else
        missing_now ? 0 : 1

evaluate(sources) =>
    s = array.size(sources)
    bar_changes = array.new_float()
    for i = 0 to 99999
        if i < s
            source = array.get(sources, i)
            array.push(bar_changes, pct_change(source, 1))
            continue
        else
            break
    bar_changes

features = array.new_float()
array.push(features, open)
array.push(features, high)
array.push(features, close)
bar_changes = evaluate(features)

plot(pct_change(open, 1))
plot(array.get(bar_changes, 0))
plot(pct_change(high, 1), color=color.aqua)
plot(array.get(bar_changes, 1), color=color.aqua)
plot(pct_change(close, 1), color=color.red)
plot(array.get(bar_changes, 2), color=color.red)
1

There are 1 best solutions below

0
On

I think you have come across the same problem I'm faced with, and it relates to using history referencing operator [] in connection with setting array element values. I've boiled it down to a very simple script illustrating the problem here.

In essence what you are doing in your code is passing array element to a pct_change() function, which uses [] operator, and then use returned result in array.push() to set array element value.

I've experienced weird results when I was trying to experiment with arrays in my scripts as soon as they've been introduced, so I started to dig in order to find the root of the problem. And it came down to the script referenced in the link above. So far I believe that Pine Script still has some bugs when it comes to arrays so we just have to wait until they'll be fixed.