[R-SIG-Finance] N'th of month working day problem
Gabor Grothendieck
ggrothendieck at gmail.com
Fri Apr 9 13:55:38 CEST 2010
The function seems to be working properly. You are asking for a day
of the month which does not exist. I assume this was written a very
long time ago since there are easier ways to do this now. yearmon
class gives an object representing the year and month of a date and if
ym is such an object then as.Date(ym) gives the first of the month and
as.Date(ym, frac = 1) gives the last of the month so:
# nth day of month or last day of month if less
nth.of.month <- function(date, n) {
ym <- as.yearmon(date)
pmin(as.Date(ym) + n - 1, as.Date(ym, frac = 1))
}
ag <- aggregate(DJd, nth.of.month(time(DJd), 31), tail, 1)
On Fri, Apr 9, 2010 at 7:01 AM, Research <risk2009 at ath.forthnet.gr> wrote:
> 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