Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert data frame with date column to timeseries

Tags:

r

xts

I've got a data frame with the following data:

>PRICE          DATE  CLOSE 1    20070103 54.700 2    20070104 54.770 3    20070105 55.120 4    20070108 54.870 5    20070109 54.860 6    20070110 54.270 7    20070111 54.770 8    20070112 55.360 9    20070115 55.760 ... 

As you can see my DATE column represents a date (yyyyMMdd) and my CLOSE column represents prices.

I now have to calculate CalmarRatio, from the PerformanceAnalytics package.

I'm new to R, so i can't understand everything, but from what i have googled to the moment i see that the R parameter to that function needs to be a time-series-like object.

Is there any way i can convert my array to a time-series object given that there might not be data for every date in a period (only for the ones i specify)?

like image 528
roirodriguez Avatar asked Jan 04 '12 19:01

roirodriguez


People also ask

How do I convert data to timeseries in R?

Creating a time seriesThe ts() function will convert a numeric vector into an R time series object. The format is ts(vector, start=, end=, frequency=) where start and end are the times of the first and last observation and frequency is the number of observations per unit time (1=annual, 4=quartly, 12=monthly, etc.).

How do you convert time series?

To convert the given dataframe with the date column to the time series object, the user first needs to import and load the xts package. The user then needs to call the xts() function with the required parameters the main need to call this function is to create the time-series object in R language and at the end use is.


1 Answers

Your DATE column may represent a date, but it is actually either a character, factor, integer, or a numeric vector.

First, you need to convert the DATE column to a Date object. Then you can create an xts object from the CLOSE and DATE columns of your PRICE data.frame. Finally, you can use the xts object to calculate returns and the Calmar ratio.

PRICE <- structure(list(   DATE = c(20070103L, 20070104L, 20070105L, 20070108L, 20070109L,            20070110L, 20070111L, 20070112L, 20070115L),   CLOSE = c(54.7, 54.77, 55.12, 54.87, 54.86, 54.27, 54.77, 55.36, 55.76)),   .Names = c("DATE", "CLOSE"), class = "data.frame",   row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9"))  library(PerformanceAnalytics)  # loads/attaches xts # Convert DATE to Date class PRICE$DATE <- as.Date(as.character(PRICE$DATE),format="%Y%m%d") # create xts object x <- xts(PRICE$CLOSE,PRICE$DATE) CalmarRatio(Return.calculate(x)) #                  [,1] # Calmar Ratio 52.82026 
like image 131
Joshua Ulrich Avatar answered Nov 07 '22 03:11

Joshua Ulrich