'Pine Script Issue Percentage Change
I am trying to create a normalized percentage change script on the interaday charts, identical to the percent setting when clicking the bottom left gear button and then clicking "percent" in the tradingview chart, allowing the user to compare two securities accumulated price movement expressed in terms of percentages on any given timeframe in this case I am using duration of only 1 day with 1 minute bars. In python it would be similar to the .rebase() function or .pct_change() function.
My Current Issues
The first is that the percentage return being returned from the script does not replicate the percentage return shown on the graph for SPY.(Although the shape of the SPY indicator line generated by the script does match the SPY line just that the value as shown in the below pictures does not match.)
My script does not start at some indexed (ie. normalized value) lets say 0% when including another security to the script. To explain my issue easily I have only included one security within the code below for this post.
CODE
- First Attempt using the ta.change() function
//Using the change() function
//@version=5
indicator("var float accum_base", format = format.percent, overlay=false)
// Add the script's inputs
symb3 = input.symbol(title="SPY", defval="AMEX:SPY")
//Retrieve Symbol Price Data
SPY = request.security(symb3, timeframe.period, close)
//Percentage Change Calc
change = ta.change(SPY, 1) / SPY[1]
//acum method to accumulate all percentage changes from first bar
var float accum = na
accum := nz(accum + change)
plot(accum)
Using the ta.change() function script SPY returns -0.12% vs the displayed SPY return of -1.66%
- Second Attempt using the ta.roc() function
//@version=5
indicator("roc function", format = format.percent, overlay=false)
// Add the script's inputs
symb3 = input.symbol(title="SPY", defval="AMEX:SPY")
//Retrieve Symbol Price Data
SPY = request.security(symb3, timeframe.period, close)
//Percentage Change Calc
base = ta.roc(SPY, 1) / SPY
//Acummulated Percentage Change
var float accum_base = na
accum_base := nz(accum_base + base)
plot(accum_base, title= "SPY", color=color.purple)
I have tried everything and could not resolve the issue. Any help would be greatly appreciated!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
