Help make this simpler – count business day
On Tue, Nov 9, 2010 at 11:49 AM, cameron <raymond.fu at invesco.com> wrote:
Help make this simpler ? count business day
I am a beginner in R and this is my first post
Want to count the day in month. ?For example
? ? ? ? ? ? ? ? Day
2010-09-01 ? 1 ? ? ?Wed
2010-09-02 ? 2 ?Thurs
2010-09-03 ? 3 ?Friday
2010-09-07 ? 4 ?Tuesday
2010-09-08 ? 5 ?Wed
2010-09-09 ? 6 ?Thursday
2010-09-10 ? 7 ?Friday
#-------------------------
library(tseries)
msft <- get.hist.quote(instrument="MSFT", start="1986-03-31",
end="2008-09-10", quote=c("O","H","L","C","A","V"), provider="yahoo",
retclass="zoo")
# tail(msft)
# ? ? ? ? ? ?Open ?High ? Low Close AdjClose ? Volume
#2008-09-03 27.00 27.18 26.84 26.90 ? ?25.73 57127700
#2008-09-04 26.74 26.89 26.35 26.35 ? ?25.21 66141900
#2008-09-05 26.03 26.22 25.63 25.65 ? ?24.54 82305200
#2008-09-08 26.21 26.33 25.67 26.12 ? ?24.99 62110800
#2008-09-09 26.20 26.60 26.05 26.10 ? ?24.97 85735700
#2008-09-10 26.52 26.86 26.25 26.44 ? ?25.29 75064900
countday<-function(z)
{
? ? ? ?z <- cbind(z,rep(0,times=nrow(z)))
? ? ? ?rng <- range(time(z))
? ? ? ?StartDate <- rng[1]
? ? ? ?EndDate ? <- rng[2]
? ? ? ?starty <- as.numeric(format(StartDate, "%Y"))
? ? ? ?endy ? <- as.numeric(format(EndDate, "%Y"))
? ? ? ?year <- starty
? ? ? ?for (year in starty:endy){
? ? ? ? ? ? ? ?for (month in 1:12){
? ? ? ? ? ? ? ? ? ? ? ?rows <- which(as.numeric(format(time(z),"%m")) == month &
as.numeric(format(time(z),"%Y")) == year )
? ? ? ? ? ? ? ? ? ? ? ?temp <- z[rows,]
? ? ? ? ? ? ? ? ? ? ? ?n <- 1:nrow(temp)
? ? ? ? ? ? ? ? ? ? ? ?z[rows,ncol(z)] <- n
? ? ? ? ? ? ? ?}
? ? ? ?}
? ? ? ?colnames(z) <- c(colnames(z[,1:(ncol(z)-1)]),"Day")
? ? ? ?return(z)
}
msft <- countday(msft)
msft
# ? ? ? ? ? ?Open ?High ? Low Close AdjClose ? Volume ? ? ? ?Day #2008-09-03 27.00 27.18 26.84 26.90 ? ?25.73 57127700 ? 2 #2008-09-04 26.74 26.89 26.35 26.35 ? ?25.21 66141900 ? 3 #2008-09-05 26.03 26.22 25.63 25.65 ? ?24.54 82305200 ? 4 #2008-09-08 26.21 26.33 25.67 26.12 ? ?24.99 62110800 ? 5 #2008-09-09 26.20 26.60 26.05 26.10 ? ?24.97 85735700 ? 6 #2008-09-10 26.52 26.86 26.25 26.44 ? ?25.29 75064900 ? 7
Try this: msft$Day <- ave(1:nrow(msft), as.yearmon(time(msft)), FUN = seq_along)
Statistics & Software Consulting GKX Group, GKX Associates Inc. tel: 1-877-GKX-GROUP email: ggrothendieck at gmail.com