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?
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With