Reputation: 313
I'm an R newbie, and I was wondering how to convert a daily data vector to a weekly one. My code is as follows:
library("quantmod")
library("xts")
library("zoo")
library(corrplot)
stock.data <- read.csv2("stocks.csv", sep = ";")
dates <- as.Date(stock.data[,"Date"], format = "%d/%m/%Y")
So far, dates
is a vector with daily data information, and stock.data
is as follows:
Date SPMILA COLCAP SPBLPGPT
1 2/01/2008 -0.002964527 -0.005017742 -0.011225818
2 3/01/2008 0.002456592 -0.002821731 0.017459207
3 4/01/2008 -0.019060974 -0.002886772 -0.002871815
4 7/01/2008 -0.010540054 0 -0.007413185
I try to convert my data to weekly as follows:
dates = to.weekly(dates, OHLC = FALSE)
but I get the error: Error in period.apply(x, ep, FUN, ...) : argument "FUN" is missing, with no default
I also tried to convert my stock.data
to weekly and see if I could then obtain the dates that way:
stock.data <- to.weekly(stock.data, OHLC = FALSE)
but then I get the error Error in try.xts(x) : Error in as.POSIXlt.character(x, tz, ...) : character string is not in a standard unambiguous format
I would appreciate any pointers since I'm not sure what to try next.
Upvotes: 1
Views: 267
Reputation: 28913
I made the /tmp/stocks.csv shown at the end. The trick was to use read.zoo
, which to.weekly()
can then work with:
z = read.zoo("/tmp/stocks.csv", format="%d/%m/%Y", sep=';', header=TRUE)
to.weekly(z, OHLC=FALSE)
Which gives:
SPMILA COLCAP SPBLPGPT
2008-01-04 -0.01906097 -0.002886772 -0.002871815
2008-01-07 -0.01054005 0.000000000 -0.007413185
stocks.csv:
Date;SPMILA;COLCAP;SPBLPGPT
2/01/2008;-0.002964527;-0.005017742;-0.011225818
3/01/2008;0.002456592;-0.002821731;0.017459207
4/01/2008;-0.019060974;-0.002886772;-0.002871815
7/01/2008;-0.010540054;0;-0.007413185
Upvotes: 1
Reputation: 1008
First error I cannot help with, but the second error is telling you r cannot interpret the date format. R does not know if you are using DD/MM/YYYY or MM/DD/YYYY.
use ?to.period to see the help, it is expecting Open, Low, High, Close data.
Converting the dates in your example to weekly will do nothing, as they are a month apart.
try
library("lubridate")
library(xts)
stringdates = c("2/1/2008", "3/1/2008", "4/1/2008")
dates <- mdy(stringdates)
values <- c(1:3)
xtsfr <- xts( values, mdy(stringdates))
xtsfr
[,1]
2008-02-01 1
2008-03-01 2
2008-04-01 3
to.weekly(xtsfr)
xtsfr.Open xtsfr.High xtsfr.Low xtsfr.Close
2008-02-01 1 1 1 1
2008-03-01 2 2 2 2
2008-04-01 3 3 3 3
to.yearly(xtsfr)
xtsfr.Open xtsfr.High xtsfr.Low xtsfr.Close
2008-04-01 1 3 1 3
I hope this is enough to help you. If not I more help understanding your issue.
Upvotes: 0