Search code examples
rquantmod

Set current subchart


I am not able to set current subchart for add_TA function (quantmod package).

curon = 2

add_TA(x, type = "l",col = "blue", lwd = 2, on=curon)

(add a line on the subchart 2)

R is giving me this error:

Error in plot_ta(x = current.chob(), ta = get("x"), on = curon, taType = NULL,  : 
 object 'curon' not found.

the command:

add_TA(x, type = "l",col = "blue", lwd = 2, on=2) 

works fine though.

NOTE: The problem only occurs when used in a function, not when in global scope. Here is a full example:

library(quantmod)

test=function(){
x=xts(runif(10),Sys.Date()+1:10)
z=1/x
chart_Series(x)
add_TA(x, type = "l",col = "green", lwd = 2)    #OK
add_TA(z, type = "l",col = "blue", lwd = 2, on=2)   #OK
curon = 2;add_TA(z, type = "l",col = "red", lwd = 2, on=curon)  #FAILS
}

test()

Solution

  • I think you must have a typo somewhere, in code you've not shown, as it works for me:

    library(quantmod)
    x=xts(runif(10),Sys.Date()+1:10)
    z=1/x
    
    chart_Series(x)
    add_TA(x, type = "l",col = "green", lwd = 2)
    curon = 2
    add_TA(z, type = "l",col = "blue", lwd = 2, on=curon)
    

    (By the way, this is what people mean by a "fully reproducible minimal example"; something you can copy and paste into a fresh R session. Unless it matters for your question, the data can be random.)

    UPDATE: Having reproduced the problem when using a function, I did find a workaround (for what I think is a quantmod bug). If you name your variable on instead of curon then it works:

    library(quantmod)
    
    test=function(){
    x=xts(runif(10),Sys.Date()+1:10)
    z=1/x
    chart_Series(x)
    add_TA(x, type = "l",col = "green", lwd = 2) 
    on=2;add_TA(z, type = "l",col = "blue", lwd = 2, on=on)
    }