6

I am a newbie for R and have got stuck here. I am trying to draw a graph with price, sma and ema.

When I call the graph from the command line it draws fine including price, sma and ema:

tickers = c("BIIB","ISRG","AIG","FITB","GE","JNY","VIAB","WFM","WMB")

x= 1

print(paste("Preparing ADX graph for :",paste(tickers[x])))
tmp <- read.csv(paste(tickers[x],".csv", sep=""),as.is=TRUE, header=TRUE, row.names=NULL) 
tmp$Date<-as.Date(tmp$Date)
ydat = xts(tmp[,-1],tmp$Date) 
names(ydat) <- c("Open","High","Low","Close","Volume","Adjusted")

# convert it into montly price
ydat.monthly <- to.monthly(ydat)

jpegname <- paste(tickers[x], "MonthlyMovingAverage.jpeg", sep="") 
jpeg( filename=jpegname,height=600, width=1600) 

lineChart(ydat.monthly["1998/"], TA=NULL, name=paste(tickers[x],"Monthly & 10 Month Moving Average"))
addSMA(10)
addEMA(10)

dev.off()

But put into function as:

MovingMonthlyAverageGraph <- function(tickers)
{

    source("code.r")
    load.packages('quantmod')   

    for (x in 1:(length(tickers)) ) 
    { 
       print(paste("Preparing ADX graph for :",paste(tickers[x])))
       tmp <- read.csv(paste(tickers[x],".csv", sep=""),as.is=TRUE, header=TRUE, row.names=NULL) 
       tmp$Date<-as.Date(tmp$Date)
       ydat = xts(tmp[,-1],tmp$Date) 
       names(ydat) <- c("Open","High","Low","Close","Volume","Adjusted")

       # convert it into montly price
       ydat.monthly <- to.monthly(ydat)

       jpegname <- paste(tickers[x], "MonthlyMovingAverage.jpeg", sep="") 
       jpeg( filename=jpegname,height=600, width=1600) 

       lineChart(ydat.monthly["1998/"], TA=NULL, name=paste(tickers[x],"Monthly & 10 Month Moving Average"))
       addSMA(10)
       addEMA(10)

       dev.off()
    }
}

and called as:

tickers = c("BIIB","ISRG","AIG","FITB","GE","JNY","VIAB","WFM","WMB")
MovingMonthlyAverageGraph(tickers)

only draws the price, but ignores the sma and ema lines.

What am I doing wrong here?

1 Answer 1

10

wrap plot around your add* calls.

plot(addSMA(10))
plot(addEMA(10))

I think you could also just add these in the lineChart call instead. (untested)

lineChart(ydat.monthly["1998/"], TA="addSMA(10);addEMA(10)", name=paste(tickers[x],"Monthly & 10 Month Moving Average"))
1
  • @user1848880, you're welcome. This is actually a common question on the r-sig-finance list (1, 2, 3), so you can look there for more detail.
    – GSee
    Nov 25, 2012 at 15:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.