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

时间:2017-03-09 11:38:10

标签: r quantmod

亲爱的堆栈溢出社区,我正在尝试使用periodReturn的quantmod函数来计算资产的回报:

HLCtest是一个“高低关闭”对象,头部(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”对象。

有人可以告诉我这个错误信息是什么告诉我以及如何解决它?

1 个答案:

答案 0 :(得分:2)

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
相关问题