问题
I'm using the latest 5 years of apple and google using the quant mode command
loadSymbols(c("AAPL", "GOOG"))
AAPL['2016::']
This is the dataset.
AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted
2016-01-04 25.6525 26.3425 25.5000 26.3375 270597600 24.36454
2016-01-05 26.4375 26.4625 25.6025 25.6775 223164000 23.75398
2016-01-06 25.1400 25.5925 24.9675 25.1750 273829600 23.28912
2016-01-07 24.6700 25.0325 24.1075 24.1125 324377600 22.30621
2016-01-08 24.6375 24.7775 24.1900 24.2400 283192000 22.42415
Can you please suggest a command I can use to choose the AAPL.Volume for a particular date of every month of every year?
Thanks.
回答1:
Try this with grep. This includes all rownames with the 4. month (April) in the AAPL data and the 5. column (AAPL.Volume).
AAPL[grep("-04-", row.names(as.data.frame(AAPL))),5]
First few rows:
head(AAPL[grep("-04-", row.names(as.data.frame(AAPL))),5])
AAPL.Volume
2007-04-02 501992400
2007-04-03 583934400
2007-04-04 476784000
2007-04-05 355516000
2007-04-09 413341600
2007-04-10 352466800
EDIT
In your case, you might first want to discard the previous years:
AAPL <- AAPL['2016::']
head([grep("-04-", row.names(as.data.frame(AAPL))),5])
AAPL.Volume
2016-04-01 103496000
2016-04-04 149424800
2016-04-05 106314800
2016-04-06 105616400
2016-04-07 127207600
2016-04-08 94326800
2. Edit
To pull out particular dates, modify the grep command like so:
head(AAPL[grep("-15$", row.names(as.data.frame(AAPL))),5])
AAPL.Volume
2016-01-15 319335600
2016-03-15 160270800
2016-04-15 187756000
2016-06-15 117780800
2016-07-15 120548000
2016-08-15 103472800
回答2:
Based on the comment we want the volume on the 15th of the month for every month from April onwards in each year. Vo(AAPL) gives the volumes. Note that POSIXlt represents months starting from 0 so April is month 3. Note that some months may not have any data on the 15th.
Vo(AAPL)[with(as.POSIXlt(AAPL), mon >= 3 & mday == 15)]
If what is actually wanted is the first date that has data on or after the 15th for April onwards in the year then first extract the volumes on the 15 and after in each month on or after April, v.ok, and then find the index of the first one of those in each month, ix, and index by it.
v.ok <- Vo(AAPL)[with(as.POSIXlt(AAPL), mon >= 3 & mday >= 15)]
ix <- tapply(seq_along(v.ok), as.yearmon(time(v.ok)), head, 1)
v.ok[ix]
来源:https://stackoverflow.com/questions/66089610/choosing-only-a-monthly-subset-using-quantmod