Search code examples
rxtsas.date

Object converted to xts but an error appears when I apply dailyReturn


I have already converted my data to an xts object and this error persists. I think it is related to my date format but, I have used the function as.Date to make sure my date format is right. Here is my code so far:

    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)

Error in to_period(xx, period = on.opts[[period]], ...) : unsupported type

A sample of my data which class is 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

When I convert to xts, my index is strange, that is, my first column, which has an X before the date:

             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"

My current version of R is ‘3.6.3’. Thank you guys!


Solution

  • You need to remove the date from your timeseries when creating an xts object. If you don't the date will appear in the matrix and will turn the matrix into a character matrix.

    Using the data.frame new35 as a starting point:

    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
    

    data:

    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")