I have a csv. file containing a prices series of a commodity from 1997 to 2018, in weekly - string format and it has exactly 52 observations per year. Which means, a week is defined as a seven day week. I want to convert this to a new data frame of xts format, containing weekly(7 day week) timeseries data ( in order to be compatible with ugarch package). I am new to xts format and do not know how to convert. Thank you very much in advance.
This is how my data look like;
week price
1997-week1 32.1
1997-week2 30.8
1997-week3 24.6
1997-week4 24.7
1997-week5 22.1
1997-week6 22.8
1997-week7 26.8
1997-week8 24
1997-week9 23.5
1997-week10 22.4
1997-week11 21.9
1997-week12 21.1
.
.
1997-week52 51.5
.
.
1998-week1 54
1998-week2 51.5
.
.
2018-week52 117.5
Assuming that what you have is the file created by the Note at the end,
create a function, week2index
which converts your week column to the form year + 0/52 for week 1, year + 1/52 for week2, ..., year + 51/52 for week52 and then with read.zoo
create a zoo object with that index. Finally convert it to a ts series.
library(zoo)
week2index <- function(x) {
d <- read.table(text = sub("-week", " ", x))
with(d, V1 + (V2 - 1) / 52)
}
z <- read.zoo("jay.dat", header = TRUE, FUN = week2index, regular = TRUE)
tt <- as.ts(z)
giving this ts series (or use the zoo series z):
> tt
Time Series:
Start = c(1997, 1)
End = c(1997, 12)
Frequency = 52
[1] 32.1 30.8 24.6 24.7 22.1 22.8 26.8 24.0 23.5 22.4 21.9 21.1
Lines <- "week price
1997-week1 32.1
1997-week2 30.8
1997-week3 24.6
1997-week4 24.7
1997-week5 22.1
1997-week6 22.8
1997-week7 26.8
1997-week8 24
1997-week9 23.5
1997-week10 22.4
1997-week11 21.9
1997-week12 21.1"
cat(Lines, file = "jay.dat")