Convert data from csv file to xts object

I have CSV files that have a date in the following format: August 25, 2004

I want to read it as an xts object to use the periodReturn function in the quantmod package.

Can I use the following file for a function?

Symbol Series Date Prev.Close Open.Price High.Price Low.Price 1 XXX EQ 25-Aug-2004 850.00 1198.70 1198.70 979.00 2 XXX EQ 26-Aug-2004 987.95 992.00 997.00 975.30 

Guide me in the same way.

+4
source share
2 answers

Unfortunately, I cannot speak for the ts part, but that is how you can convert your dates to the correct format, which can be read by other functions as dates (or time). You can import your data into data.frame as usual ( see here if you skipped it ). You can then convert the Date column to the POSIXlt ( POSIXt ) class using the strptime function.

 nibha <- "25-Aug-2004" # this should be your imported column lct <- Sys.getlocale("LC_TIME"); Sys.setlocale("LC_TIME", "C") #temporarily change locale to C if you happen go get NAs strptime(nibha, format = "%d-%b-%Y") Sys.setlocale("LC_TIME", lct) #revert back to your locale 
+3
source

Try it. We get rid of the inconvenience columns and specify the time index format, then convert to xts and use the dailyReturn function:

 Lines <- "Symbol Series Date Prev.Close Open.Price High.Price Low.Price 1 XXX EQ 25-Aug-2004 850.00 1198.70 1198.70 979.00 2 XXX EQ 26-Aug-2004 987.95 992.00 997.00 975.30" library(quantmod) # this also pulls in xts & zoo z <- read.zoo(textConnection(Lines), format = "%d-%b-%Y", colClasses = rep(c(NA, "NULL", NA), c(1, 2, 5))) x <- as.xts(z) dailyReturn(x) 

Of course, textConnection(Lines) is to save the example by itself and actually replace it with something like "myfile.dat" .

+3
source

Source: https://habr.com/ru/post/1336424/


All Articles