我已经将我的数据转换为xts对象,并且该错误仍然存在。我认为它与我的日期格式有关,但是我使用as.Date函数来确保我的日期格式正确。到目前为止,这是我的代码:
library(quantmod)
library(ggplot2)
library(PerformanceAnalytics)
library(GetTDData)
library(openair)
library(dplyr)
library(devtools)
ntnb <- download.TD.data('NTN-B')
ntnb35 <- read.TD.files(dl.folder = 'TD Files',
maturity = '150535')
new35<-ntnb35%>%select(ref.date,yield.bid,price.bid,asset.code,matur.date)%>%filter(ref.date>=as.Date("2016-01-01"))
new35$ref.date<-as.Date(new35$ref.date,format="%Y-%m-%d")
new35_xts<-xts(new35,order.by=new35$ref.date)
dailyReturn(new35_xts)
to_period(xx,period = on.opts [[period]],...)中的错误:不支持的类型
我的数据示例,其类为data.frame:
ref.date yield.bid price.bid
1 2016-01-04 0.0737 2425.21
2 2016-01-05 0.0735 2431.68
3 2016-01-06 0.0727 2453.29
4 2016-01-07 0.0724 2462.39
5 2016-01-08 0.0732 2443.98
当我转换为xts时,我的索引很奇怪,也就是说,我的第一列在日期之前有一个X:
ref.date yield.bid price.bid
X2016.01.04 "2016-01-04" "0.0737" "2425.21"
X2016.01.05 "2016-01-05" "0.0735" "2431.68"
X2016.01.06 "2016-01-06" "0.0727" "2453.29"
X2016.01.07 "2016-01-07" "0.0724" "2462.39"
X2016.01.08 "2016-01-08" "0.0732" "2443.98"
X2016.01.11 "2016-01-11" "0.0737" "2432.90"
X2016.01.12 "2016-01-12" "0.0735" "2439.33"
X2016.01.13 "2016-01-13" "0.0734" "2443.28"
我当前的R版本是“ 3.6.3”。谢谢你们!
创建xts对象时,您需要从时间序列中删除日期。如果不这样做,则日期将出现在矩阵中,并将矩阵转换为字符矩阵。
使用data.frame new35作为起点:
library(quantmod)
# Make sure you don't have the data in the data for the xts matrix.
# The index is defined in the order.by
new35_xts <- xts(new35[, -1], order.by = new35$ref.date)
dailyReturn(new35_xts)
daily.returns
2016-01-04 0.000000000
2016-01-05 -0.002713704
2016-01-06 -0.010884354
2016-01-07 -0.004126547
2016-01-08 0.011049724
数据:
new35 <- structure(list(ref.date = structure(c(16804, 16805, 16806, 16807,
16808), class = "Date"), yield.bid = c(0.0737, 0.0735, 0.0727,
0.0724, 0.0732), price.bid = c(2425.21, 2431.68, 2453.29, 2462.39,
2443.98)), row.names = c("1", "2", "3", "4", "5"), class = "data.frame")
非常感谢!代码超好!