[R-SIG-Finance] N'th of month working day problem
Research
risk2009 at ath.forthnet.gr
Fri Apr 9 13:01:16 CEST 2010
Dear all,
Some time ago I received some very kind help (special thanks to Gabor)
to construct a function that isolates the n'th working day of each
month for zoo object (time series) to create monthly data from daily
observations.
I found out that the code works fine except for the 29 till 31st dates
of each month as it skips some months (February for example).
If you could help me isolate the problem I would be grateful as I can
not find a way to explain to R to keep the last working day of month if
I choose the 29th, 30th or 31st dates...
I enclose a working version of the function and a script for demo purposes.
Many thanks in advance,
Costas
library(fImport)
library(zoo)
DJ<-yahooSeries("^DJI", frequency="daily", nDaysBack=10000)
DJd<-as.zoo(DJ[,4])
### Choose number of day for month
chooseday<-function(z, day)
{
# z.na is same as z but with missing days added using NAs
# Its formed by merging z with a zoo-width series containing all days.
rng <- range(time(z))
z.na <- merge(z, zoo(, seq(rng[1], rng[2], by = "day")))
# form a series that has NAs wherever z.na does but has 1, 2, 3, ...
# instead of z.na's data values and then use na.locf to fill in NAs
idx <- na.locf(seq_along(z.na) + (0 * z.na))
# pick off elements of z.na corresponding to i'th of month
noofday <- paste(day)
if (day<10) noofday<-paste("0",day, sep="")
tempdata<-z.na[idx[format(time(z.na), "%d") == noofday]]
return(tempdata)
}
length(chooseday(DJd,1))
length(chooseday(DJd,2))
length(chooseday(DJd,31))
length(chooseday(DJd,30))
length(chooseday(DJd,29))
length(chooseday(DJd,28))
tail(chooseday(DJd,31))
More information about the R-SIG-Finance
mailing list