从函数调用时,addSMA 未绘制在图形上 [英] addSMA not drawn on graph when called from function

查看:45
本文介绍了从函数调用时,addSMA 未绘制在图形上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 R 的新手,一直被困在这里.我正在尝试用价格、sma 和 ema 绘制图表.

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

当我从命令行调用图形时,它可以很好地绘制包括价格、sma 和 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()

但投入函数为:

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()
    }
}

并称为:

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

只绘制价格,而忽略 sma 和 ema 线.

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

我在这里做错了什么?

推荐答案

plot 包裹在您的 add* 调用中.

wrap plot around your add* calls.

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

我认为您也可以将这些添加到 lineChart 调用中.(未经测试)

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

这篇关于从函数调用时,addSMA 未绘制在图形上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆