0

I have a set of data from historical stock prices for publicly traded companies on the NASDAQ and NYSE. I've used the following code to download data on Amazon's stock price and get the times the data was sampled.

library(quantmod)
amzn <- getSymbols("AMZN",auto.assign=FALSE)
sampleTimes <- index(amzn)

Then I used grepl to get a count of how many values were collected in 2012. Now I need to get a count of how many of those values occurred on Mondays.

I've tried several different approaches, but none has been effective. I'm thinking that the lubridate package should be useful, but I can't figure out just how. POSIXlt should also be helpful, but I also can't think of an effective way to use it.

This must be a very simple problem, but I can't seem to wrap my brain around it.

Please help.

user3682294
  • 29
  • 1
  • 6

3 Answers3

3

I think this is what you're after:

table(weekdays(sampleTimes))

##    Friday    Monday  Thursday   Tuesday Wednesday 
##       373       350       376       381       382

Edit per the OP's comments:

do.call(rbind, lapply(split(sampleTimes, substring(sampleTimes, 1, 4)), function(x) {
    table(weekdays(x))
}))

##      Friday Monday Thursday Tuesday Wednesday
## 2007     51     48       51      50        51
## 2008     50     48       50      52        53
## 2009     49     48       51      52        52
## 2010     50     47       51      52        52
## 2011     51     46       51      52        52
## 2012     51     47       51      50        51
## 2013     51     48       50      52        51
## 2014     20     18       21      21        20
Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519
  • This is perfect, except that I'm trying to get a list of instances within sampleTimes that occurred on Mondays in the year 2012. So there seems to be one missing piece. – user3682294 May 28 '14 at 18:17
  • I thought you said you could do the years? See my edit. – Tyler Rinker May 28 '14 at 20:25
  • Yes, sorry. I was able to extract the years, but couldn't figure out how to write a function that would BOTH extract the year 2012 and instances of Mondays. – user3682294 May 28 '14 at 20:43
1

You can quite simply achieve this using the lubridate package as below:

Edit: replaced nrow() to length()

> library(lubridate)
> sampleTimes <- ymd(sampleTimes)
> length(subset(sampleTimes, year(sampleTimes) == 2012 & wday(sampleTimes, label=T) == "Mon"))
[1] 47
Rahul Premraj
  • 1,595
  • 14
  • 13
1

Just use weekdays(.) == "Monday" as a logical index into sampleTimes and add the requirement that they be in 2012:

 head( sampleTimes[ weekdays(sampleTimes)=="Monday"] )
[1] "2007-01-08" "2007-01-22" "2007-01-29" "2007-02-05" "2007-02-12" "2007-02-26"

> head( sampleTimes[ weekdays(sampleTimes)=="Monday" & substr(sampleTimes, 1,4)=="2012"] )
[1] "2012-01-09" "2012-01-23" "2012-01-30" "2012-02-06" "2012-02-13" "2012-02-27"
IRTFM
  • 258,963
  • 21
  • 364
  • 487