R 代码 - periodReturn 函数的使用(quantmod 包)

R code - Use of periodReturn function (quantmod package)

亲爱的 Stack overflow 社区,我正在尝试使用 periodReturn 的 quantmod 函数计算资产的 returns:

HLCtest 是一个 "High Low Close" 对象,head(HLCtest) 给出:

##       Date          High     low     Close
##1  1991-01-01 GMT  1517.93  1517.93  1517.93   
##2  1991-01-02 GMT  1509.58  1487.96  1505.10
##3  1991-01-03 GMT  1540.22  1500.54  1539.50
##4  1991-01-04 GMT  1552.15  1533.77  1547.66
##5  1991-01-07 GMT  1524.38  1501.26  1507.87
##6  1991-01-08 GMT  1507.37  1474.79  1500.24

> yearlyReturn(HLCtest, subset=NULL, type='arithmetic', leading=TRUE)

我收到以下错误消息:

> Error in try.xts(x) : 
  Error in as.POSIXlt.character(x, tz, ...) :   character string is not in a    standard unambiguous format

我用过:

> strftime(HLCtest$Date, format ="", tz="GMT", usetz = TRUE)

确保日期格式符合 ISO8601 标准。

还有: > is.HLC(HLCtest) 以确保该对象是 "High Low Close" 对象。

有人可以告诉我这条错误消息告诉我什么以及如何解决吗?

yearlyReturn 不知道如何将您的 data.frame 转换为 xts 对象。这是因为它使用 try.xts 尝试将其转换为 xts 对象,并且 try.xts 期望 data.frame 行名称包含日期。

最简单的解决方案是自己创建一个 xts 对象,然后将其传递给 yearlyReturn

# sample data
y <- structure(list(Date = structure(c(7670, 7671, 7672, 7673, 7676, 
7677), class = "Date"), High = c(1517.93, 1509.58, 1540.22, 1552.15, 
1524.38, 1507.37), low = c(1517.93, 1487.96, 1500.54, 1533.77, 
1501.26, 1474.79), Close = c(1517.93, 1505.1, 1539.5, 1547.66, 
1507.87, 1500.24)), .Names = c("Date", "High", "low", "Close"),
row.names = c(NA, -6L), class = "data.frame")
# make xts object
x <- xts(y[,-1], y[,1])
# call *lyReturn
dailyReturn(x)
#            daily.returns
# 1991-01-01   0.000000000
# 1991-01-02  -0.005500912
# 1991-01-03   0.020297036
# 1991-01-04   0.007745647
# 1991-01-07  -0.017891312
# 1991-01-08  -0.011158635