addSMA not drawn on graph when called from functio

2020-02-01 04:39发布

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?

标签: r quantmod
1条回答
来,给爷笑一个
2楼-- · 2020-02-01 05:02

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"))
查看更多
登录 后发表回答