Search code examples
rquantmod

How to overlay multiple TA in new plot using quantmod?


We can plot candle stick chart using chart series function chartSeries(Cl(PSEC)) I have created some custom values (I1,I2 and I3) which I want to plot together(overlay) outside the candle stick pattern. I have used addTA() for this purpose

chartSeries(Cl(PSEC)), TA="addTA(I1,col=2);addTA(I2,col=3);addTA(I3,col=4)")

The problem is that it plots four plots for Cl(PSEC),I1,I2 and I3 separately instead of two plots which I want Cl(PSEC) and (I1,I2,I3)

EDITED

For clarity I am giving a sample code with I1, I2 and I3 variable created for this purpose

library(quantmod)
PSEC=getSymbols("PSEC",auto.assign=F)
price=Cl(PSEC)
I1=SMA(price,3)
I2=SMA(price,10)
I3=SMA(price,15)
chartSeries(price, TA="addTA(I1,col=2);addTA(I2,col=3);addTA(I3,col=4)")

Solution

  • Here is an option which preserves largely your original code. You can obtain the desired result using the option on=2 for each TA after the first:

    library(quantmod)
    getSymbols("PSEC")
    price <- Cl(PSEC)
    I1 <- SMA(price,3)
    I2 <- SMA(price,10)
    I3 <- SMA(price,15)
    chartSeries(price, TA=list("addTA(I1, col=2)", "addTA(I2, col=4, on=2)",
                               "addTA(I3, col=5, on=2)"), subset = "last 6 months")
    

    enter image description here

    If you want to overlay the price and the SMAs in one chart, you can use the option on=1 for each TA.

    Thanks to @hvollmeier who made me realize with his answer that I had misunderstood your question in the previous version of my answer.

    PS: Note that several options are described in ?addSMA(), including with.col which can be used to select a specific column of the time series (Cl is the default column).