我正在尝试编写一个会返回股票单日回报的公式,但我相信我对periodReturn
subset
字段的数据类型有问题
periodReturn(ticker,period='daily',subset='20161010::20161010')
有效但
dayReturn <- function(ticker,date) {
ticker <- c(MSFT)
date <- c(20161010)
dayreturn <- periodReturn(ticker,period='daily',paste("subset='",date,"::",date,"'"))
dayreturn
}
给出错误
dayReturn(msft,20161010)
daily.returns
Warning messages:
1: In as_numeric(YYYY) : NAs introduced by coercion
2: In as_numeric(MM) : NAs introduced by coercion
3: In as_numeric(DD) : NAs introduced by coercion
>
提前感谢任何建议!
答案 0 :(得分:2)
您的dayReturn
函数中存在一些语法错误。
以下是从函数内部提取的可重现代码:
library(quantmod)
getSymbols("MSFT")
ticker <- c(MSFT)
date <- c("20161010")
dayreturn <- periodReturn(ticker,period='daily',subset = paste0(date,"::",date,"'"))
您的错误:
date
想要成为字符串,而不是数字。subset = "YYYYMMDD::YYYYMMDD"
一侧使用subset = "YYYY-MM-DD::YYYY-MM-DD"
或(periodReturn
)。 您的功能可以更正确地工作:
dayReturn <- function(ticker, date1 , date2) {
dayreturn <- periodReturn(ticker,period='daily',subset = paste0(date1,"::",date2,"'"))
dayreturn
}
dayReturn(MSFT, "20161010", "20161012")
# daily.returns
# 2016-10-10 0.004152284
# 2016-10-11 -0.014645107
# 2016-10-12 -0.001398811