将 quantmod periodReturn 与环境中变量的索引结合使用
我编写了以下函数来自动评估错过特定股票交易的最佳/最差日子的影响。不幸的是,该函数的一部分似乎失败了:
library(quantmod)
missingDays<- function(ticker,dmiss=10,type="best",period="days",fdate="2000-01-01",tdate=Sys.Date()) {
getSymbols(ticker,from=fdate,to=tdate) #quantmod to pull ticker info
d<-get(ls()[1])
x<-as.data.frame(periodReturn(Cl(d),period=period))
x<- x[order(x[1]),]
if(type=="best") {
(((mean(x[1:(length(x)-dmiss)],na.rm=TRUE)+1)^(251))-1)*100 #average daily return, annualized
} else {
(((mean(x[dmiss:(length(x))],na.rm=TRUE)+1)^(251))-1)*100 #average daily return, annualized
}
}
missingDays("^GSPC",10,type="best",period="daily",fdate="2000-01-01")
错误显然发生在这两行代码中:
d<-get(ls()[1])
x<-as.data.frame(periodReturn(Cl(d),period=period))
这很奇怪,因为当我直接运行它而不是在函数中运行时,它工作正常。它似乎无法将 d 识别为 xts 对象。
如果我错过了一些明显的事情,我很抱歉 - 我已经这样做了一段时间了。
非常感谢您的帮助。
I've written the following function to autmoatically assess the effect of missing the best/worst days of trading ina given stock. Unfortunately, one part of the function seems to fail:
library(quantmod)
missingDays<- function(ticker,dmiss=10,type="best",period="days",fdate="2000-01-01",tdate=Sys.Date()) {
getSymbols(ticker,from=fdate,to=tdate) #quantmod to pull ticker info
d<-get(ls()[1])
x<-as.data.frame(periodReturn(Cl(d),period=period))
x<- x[order(x[1]),]
if(type=="best") {
(((mean(x[1:(length(x)-dmiss)],na.rm=TRUE)+1)^(251))-1)*100 #average daily return, annualized
} else {
(((mean(x[dmiss:(length(x))],na.rm=TRUE)+1)^(251))-1)*100 #average daily return, annualized
}
}
missingDays("^GSPC",10,type="best",period="daily",fdate="2000-01-01")
The error clearly happens in these two lines of code:
d<-get(ls()[1])
x<-as.data.frame(periodReturn(Cl(d),period=period))
This is very odd, because when I run this directly, rather than in a function, it works fine. It seems to not be able to identify d
as an xts object.
My apologies if I've missed something obvious - I've been at this a while.
Much thanks for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要像在函数中那样使用
getSymbols
。设置auto.assign=FALSE
并将getSymbols
的输出直接分配给d
:这在
?getSymbols<中有详细描述/代码>。我鼓励你仔细阅读它。
更新:
现在我想得更多了,
missingDays
函数接受getSymbols
调用的输出可能会更好。这样您就不必下载不同参数集的数据。Don't use
getSymbols
like that inside a function. Setauto.assign=FALSE
and assign the output ofgetSymbols
tod
directly:This is all described in detail in
?getSymbols
. I would encourage you to read it carefully.UPDATE:
Now that I think about it a bit more, it would probably be better for the
missingDays
function to accept the output from a call togetSymbols
. Then you would avoid having to download the data for different sets of parameters.这是因为
ls
正在函数 envir 内部进行计算。使用 .GlobalEnv 让它在全局环境中查找。我不确定 get 函数中是否需要 envir。但我想这不会造成伤害。
华泰
That's because
ls
is evaluating inside the function envir. Use.GlobalEnv
to have it look it up in the global environment.I'm not sure if the envir in get function is needed. But I guess it won't hurt.
HTH