Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

r - addSMA not drawn on graph when called from function

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...