How to find out how many trading days in each month in R?
我有一个这样的数据框。时间跨度为10年。因为这是中国的市场数据,而中国有农历假期。因此,根据西方日历,每年都有不同的假期时间。
在假日期间,股票市场不会开放,因此它是非交易日。周末也是非交易日。
我想找出哪一年中哪个月份的交易日最少,最重要的是,那是哪个交易日。
没有重复的日子。
1 2 3 4 5 6 7 | date change open high low close volume 1 1995-01-03 -1.233 637.72 647.71 630.53 639.88 234518 2 1995-01-04 2.177 641.90 655.51 638.86 653.81 422220 3 1995-01-05 -1.058 656.20 657.45 645.81 646.89 430123 4 1995-01-06 -0.948 642.75 643.89 636.33 640.76 487482 5 1995-01-09 -2.308 637.52 637.55 625.04 625.97 509851 6 1995-01-10 -2.503 616.16 617.60 607.06 610.30 606925 |
chron和bizdays包处理工作日,但实际上都没有包含可用的假期日历,限制了它们的实用性。
假设您已定义假日的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | library(chron) library(zoo) st <- as.yearmon("2001-01") en <- as.yearmon("2010-12") ym <- seq(st, en, 1/12) # sequence of year/months of interest # no of business days in each yearmonth busdays <- sapply(ym, function(x) { s <- seq(as.Date(x), as.Date(x, frac = 1),"day") sum(!is.weekend(s) & !is.holiday(s)) }) # data frame with one row per year/month yr <- as.integer(ym) DF <- data.frame(year = yr, month = cycle(ym), yearmon = ym, busdays) # data frame with one row per year wx.min <- ave(busdays, yr, FUN = function(x) which.min(x) == seq_along(x)) DF[wx.min == 1, ] |
给予:
1 2 3 4 5 6 7 8 9 10 11 | year month yearmon busdays 2 2001 2 Feb 2001 20 14 2002 2 Feb 2002 20 26 2003 2 Feb 2003 20 38 2004 2 Feb 2004 20 50 2005 2 Feb 2005 20 62 2006 2 Feb 2006 20 74 2007 2 Feb 2007 20 95 2008 11 Nov 2008 20 98 2009 2 Feb 2009 20 110 2010 2 Feb 2010 20 |
如果没有重复的天数,则可以通过以下方式计算每月和每年的天数:
1 2 3 4 | library(data.table) "maxx"))), .Names = c("X2005","X2006","X2007","X2008")) library(lubridate) dt <- as.data.table(dt) dt_days <- dt[, .(count_day=.N), by=.(year(date), month(date))] |
然后您只需要执行此操作即可获取最小值:
1 | dt_days[count_day==min(count_day)] |