计算 NYSE 交易日的函数

2024-01-27

希望有人可以提供一个给定日期的函数,它将返回纽约证券交易所当月的交易日。

如果考虑到假期,那就是额外的好处,如果没有,我也不太担心。

提前致谢!


我的个人包中有一个函数,名为TradingDates使用假期的 日历从timeDate http://cran.r-project.org/package=timeDate包裹 返回指定年份中所有交易日的日期。包括我 该函数的代码位于本文末尾以及函数中PrevTradingDate and NextTradingDate这是我们的动机TradingDates功能。

一旦你获取了该代码,就可以很容易地创建一个返回的函数 给定日期属于该月的哪个交易日。现在,输入日期 必须是(单个)交易日期,但这可以很容易地更改,具体取决于 您的偏好。

TradingDayOfMonth <- function(Date, FUN=holidayNYSE, ...) {
  if (length(Date) > 1) stop('not vectorized; Date should be length 1')
  Date <- as.Date(Date, ...)
  tdy <- TradingDates(format(Date, "%Y"), FUN=FUN) #trading dates in year
  if (!Date %in% tdy) stop("Date is not a Trading Date")
  tdm <- tdy[format(tdy, "%m") %in% format(Date, "%m")] # trading dates in the same month as "Date"
  which(tdm == Date)
}

R> PrevTradingDate()
[1] "2012-11-02"
R> NextTradingDate()
[1] "2012-11-05"
R> TradingDayOfMonth(PrevTradingDate())
[1] 2
R> TradingDayOfMonth(NextTradingDate())
[1] 3
R> TradingDayOfMonth('2012-11-15')
[1] 11

上述工作所需的代码:

#' Get Trading Dates for one or more years
#'
#' Get a vector of dates of non-holiday weekdays.
#' 
#' This uses holiday calendar functions (\code{holidayNYSE} by default)
#' from the \emph{timeDate} package.  If \emph{timeDate} is not loaded, it 
#' will be temporarily loaded, then unloaded \code{on.exit}.
#' 
#' @param year vector of 4 digit years or something that is coercible to 
#'   a vector 4 digit years via \code{as.numeric}
#' @param FUN a function that takes a \code{year} argument and returns a vector
#'   that can be coerced to a \code{Date}.  \code{holidayNYSE} by default. Most
#'   likely, this will be one of:  \sQuote{holidayLONDON}, \sQuote{holidayNERC}, 
#'   \sQuote{holidayNYSE}, \sQuote{holidayTSX}, \sQuote{holidayZURICH}
#' @return a vector of all dates in \code{years} that are weekdays and not 
#'   holidays.
#' @author GSee
#' @examples
#' \dontrun{
#' TradingDates(2012)
#' TradingDates(2010:2011)
#' }
#' @export
TradingDates <- function(year=format(Sys.Date(), "%Y"), FUN=holidayNYSE) {
  # the next few lines should be removed when this code is added to a package
  # that Imports timeDate
  if (!"package:timeDate" %in% search()) {
    suppressPackageStartupMessages({ 
      if (!require(timeDate)) {
        stop("timeDate must be installed to use this function.")
      }
    })
    on.exit(detach(package:timeDate, unload=TRUE))
  }
  ## End of code that should be removed when this is added to a package
  year <- as.numeric(year)
  fun <- match.fun(FUN)
  do.call('c', lapply(year, function(y) {
    holidays <- as.Date(fun(year=y))
    all.days <- seq.Date(as.Date(paste(y, '01-01', sep='-')), 
                         as.Date(paste(y, '12-31', sep='-')), by='days')
    nohol <- all.days[!all.days %in% holidays]
    nohol[!format(nohol, '%w') %in% c("6", "0")] #neither holiday nor weekend
  }))
}


#' Get Date of previous (next) trading day
#' 
#' Get the Date of the previous (next) trading day.
#' 
#' For \code{PrevTradingDate}, \code{n} is the number of days to go back. So,
#' if \code{n} is 2 and today is a a Monday, it would return the date of the
#' prior Thursday because that would be 2 trading days ago.
#' \code{n} works analogously in \code{NextTradingDate}.
#'
#' The maximum value that \code{n} can be is the total number of days in the
#' year prior to \code{Date} plus the total number of years in the current 
#' year of \code{Date}.  So, on the last day of the year, the max value of
#' \code{n} will usually be \code{504} (because most years have 252 trading 
#' days).  One the first day of the year, the max value of \code{n} will usually
#' be \code{252}.
#'
#' @param n number of days to go back. 1 is the previous trading day; 2 is the
#'   trading day before that, etc.  \code{n} should be less than 365, but see
#'   details
#' @param Date a \code{Date} or something that can be coerced to a \code{Date}
#' @return \code{PrevTradingDate} returns the date of the previous trading day 
#' up to, but not including, \code{Date}.  \code{NextTradingDate} returns the 
#' date of the next trading day.
#' @author GSee
#' @seealso \code{\link{TradingDates}}
#' @examples
#' \dontrun{
#' PrevTradingDate()
#' PrevTradingDate('2012-01-03')
#' NextTradingDate()
#' NextTradingDate('2012-12-24')
#' }
#' @export
#' @rdname PrevTradingDate
PrevTradingDate <- function(Date=Sys.Date(), n=1) {
  stopifnot(require(xts)) #remove this line when this is added to a package that Imports xts (needed for first/last)
  D <- as.Date(Date)
  y <- as.numeric(format(D, "%Y"))
  trading.days <- TradingDates(y)
  out <- trading.days[trading.days < Date]
  if (length(out) >= n) {
    first(last(out, n))
  } else { 
    prev.year.td <- TradingDates(y - 1)
    max.n <- length(out) + length(prev.year.td)
    if (n > max.n) stop("'n' is too large. Try something less than 252.")
    new.n <- n - length(out) # we need this many trading days from previous year
    # if it's the 1st trading day of the year, return the last trading date of
    # previous year
    first(last(TradingDates(y - 1), new.n))
  } 
}

#' @export
#' @rdname PrevTradingDate
NextTradingDate <- function(Date=Sys.Date(), n=1) {
  stopifnot(require(xts)) #remove this line when this is added to a package that Imports xts (needed for first/last)
  D <- as.Date(Date)
  y <- as.numeric(format(D, "%Y"))
  trading.days <- TradingDates(y)
  out <- trading.days[trading.days > Date]
  if (length(out) >= n) {
    last(first(out, n))
  } else { 
    next.year.td <- TradingDates(y + 1)
    max.n <- length(out) + length(next.year.td)
    new.n <- n - length(out) # how many trading days we need from next year
    if (n > max.n) stop("'n' is too large. Try something less than 252.")
    # if it's the last trading day of the year, return the first trading date of
    # next year
    last(first(TradingDates(y + 1), new.n))
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

计算 NYSE 交易日的函数 的相关文章

  • R 中 nlme 包中的 gls 函数出错

    我不断收到这样的错误 Error in coef lt corARMA tmp value c 18 3113452983211 1 56626248550284 Coefficient matrix not invertible 或者像这
  • 如何从R中串扰的filter_select中删除(全部)?

    我遵循图 16 7 的示例https plotly r com client side linking html https plotly r com client side linking html并且无法弄清楚为什么有一个名为 全部 的
  • R 带有列和行的分面 qqplots

    我需要使用按行和列的构面创建 qqplot 我了解如何用列和行绘制分面图 但我不确定如何设置我的数据 最终 我想按列和行对数据集进行分组 然后按升序对 建模 结果和 观察到 结果进行排序 同时添加带有 行 组的列和带有 列 组的列 我一直在
  • 关于子组的新列和另一列中的百分比范围

    我有一个如下所示的示例 df df test lt data frame Group Name c Group1 Group2 Group1 Group2 Group2 Group2 Group1 Sub group name c A A
  • 使用 2 个向量参数翻转函数

    我想对需要 2 个向量参数的函数应用滚动 这是使用 data table 的示例 不起作用 library data table df lt as data table cbind data frame x 1 100 y 101 200
  • 根据 R 中的字符串模式选择行

    假设我有以下数据 df lt data frame name c TO for Turnover for people HC people Hello world beenie man apple pears TO is number c
  • 如何在 R Markdown 中的内联 LateX 方程中输出 R 变量的值(即动态更新)

    我无法找到一种方法将 r 代码实现到 R markdown 中的内联 LateX 方程中 目标是如果变量 值 发生变化 则不必对它们的值进行硬编码 Given values lt c 1 4 2 5 7 9 avg lt sum value
  • XLConnect 无法确定 JAVA_HOME 错误

    感谢您的帮助 我正在尝试运行 XLconnect 但收到此错误消息 gt library XLConnect lib loc C Users 1144143929 Documents R win library 2 15 Error onL
  • 使用神经网络包进行多项分类

    这个问题应该很简单 但文档没有帮助 我正在使用 R 我必须使用neuralnet多项式分类问题的包 所有示例均针对二项式或线性输出 我可以使用二项式输出进行一些一对一的实现 但我相信我应该能够通过使用 3 个单元作为输出层来做到这一点 其中
  • 跨类别和列自动化卡方

    我有一个调查数据框 其中包含几个问题 列 编码为 1 同意 0 不同意 受访者 行 根据 年龄 年轻 中年 老年 地区 东 中 西 等指标进行分类 大约有30个类别总共 3个年龄 3个地区 2个性别 11个职业等 在每个指标中 类别不重叠且
  • 使用faceting()时如何连接geom_point()和geom_line?

    我有一个问题 但我在互联网上没有找到任何相关信息 我很高兴得到一些提示 我有一个数据集 其中 x 轴是离散的 但我想将这些点相互连接 我可以做到 我的问题是当我添加分面选项时 我无法再将这些点相互链接起来 我找到了一个替代方案 但看起来不太
  • Shiny:从DT数据表中选定的行获取信息

    我们正在尝试重新创建示例 https demo shinyapps io 029 row selection https demo shinyapps io 029 row selection 使用DT包来渲染数据帧而不是shiny包 DT
  • 在 Windows / Linux 中创建 Mac 包

    我自己努力制作一个 r 包 我按照 stackoverflow 中上一个问题的说明进行操作如何为外行开发软件包 http cran r project org bin windows Rtools 以下是我根据上一个问题采取的步骤 在新的
  • 在ggplot2中,箱线图线的末尾代表什么?

    我找不到箱线图线条端点代表什么的描述 For example here are point values above and below where the lines end 我意识到盒子的顶部和底部是第 25 个和第 75 个百分位数
  • R 中具有 p 值的相关矩阵

    假设我想要传导相关矩阵 library dplyr data iris iris gt select if is numeric gt cor y iris Petal Width method spearman gt round 2 现在
  • 如何不显示 ggplot 轴上的所有标签?

    I m trying to using ggplot2 to plot this But as you can see on the x axis you can t read anything 那么如何在 x 轴上显示每 10 年的值呢
  • 连接树状图和热图

    我有一个heatmap 一组样本的基因表达 set seed 10 mat lt matrix rnorm 24 10 mean 1 sd 2 nrow 24 ncol 10 dimnames list paste g 1 24 sep p
  • R ggplot2 分面保持比率但覆盖/定义输出图大小

    我目前正在使用 ggplot2 来比较不同组的统计数据 每个组属于不同的区域 这是通过运行 R 脚本的 Web 应用程序 tikiwiki CMS 插件 R 完成的 每个区域我可以有 2 到 30 个或更多组 相同的 R 脚本针对唯一网页中
  • 如何将 Shiny 中生成的反应图传递到 Rmarkdown 以生成动态报告

    简而言之 我希望能够通过单击按钮从我的闪亮应用程序生成动态 Rmarkdown 报告文件 pdf 或 html 为此 我想我将使用 Shiny 的参数化报告 但不知何故 我无法将单个谜题转移到所需的目标 使用此代码 我们可以在 R Shin
  • Matlab 中是否有相当于 R 的 dput() 的函数?

    Matlab 中是否有相当于 R 的 dput 的函数 dput 将 R 对象的 ASCII 文本表示形式写入文件或连接 UPDATE 1 添加了递归和对单元格的支持 UPDATE 2 添加了对结构的支持 UPDATE 3 增加了对逻辑 整

随机推荐

  • 如何根据名称删除docker镜像?

    我想删除名称包含给定字符串的所有版本的 docker 映像 imagename 我已经尝试过以下方法 但似乎不起作用 docker images grep imagename xargs I docker rmi 请尝试以下操作 docke
  • Openfire Android PubSub 订阅请求批准

    我是 Openfire 的新手 因此我对 pubsub 功能有疑问 实际上 我已经创建了一个节点设置访问模型 as 授权 如下所示 PubSubManager mgr new PubSubManager xmpp getConnection
  • React Native 在 OnChange 中获取 TextInput 的名称

    我正在尝试为多个 TextInput 制作通用的 onChange 处理程序 然而 当我访问该事件时 我能得到的最好的结果是 event nativeEvent 它有 3 个键 事件计数 目标和文本 目标只是一个数字 我从文档中意识到 名称
  • MVC 5 种子用户和角色

    我一直在玩新的 MVC 5 我有一些使用代码优先迁移的模型 控制器和视图设置 我的问题是如何播种用户和角色 目前 我在 Configuration cs 的 Seed 方法中播种了一些参考数据 但在我看来 只有在某些内容首次到达 Accou
  • 如何在容器 div 内拥有具有固定页眉和页脚的可滚动正文?

    我有一个容器 div 有两个孩子 div 里面的元素 我想安置一个孩子 div 在顶部和其他孩子 div 在容器的底部 div 中间部分 内容 应在顶部和底部子项之间滚动 div 元素 我想要两个孩子 div 容器内的元素 div 具有固定
  • 单个文件中的多个类

    我无法将多个类放入一个文件中 例如 当我的文件如下所示 public class FirstClass public class SecondClass public class ThirdClass 我在编译过程中遇到错误 我不太确定是什
  • 加密 web.config 中的 appSettings

    我正在开发一个网络应用程序 它需要将用户名和密码存储在 web Config 中 它还引用一些由网络应用程序本身而不是客户端请求的 URL 我知道 Net 框架不允许提供 web config 文件 但我仍然认为以纯文本形式保留此类信息是不
  • 如何为Windows 7 32位系统安装tensorflow?我在我的系统中安装了python 3.5(32位)并安装了anaconda 3.4.4(32位)

    我只有32位系统 所以我安装了python 3 5 64位 发生错误 所以我成功安装了python 32位 然后我跟着那个文档 http tensorflow org install http tensorflow org install
  • 在 python 中将 IPOPT 与 Openmdao(或 pyoptsparse)结合使用

    大家好 我有一个小问题 我正在使用 openmdao 和 pyOptSparseDriver 它适用于某些求解器 例如 SLSQP PSQP 因此安装没有问题 现在我想用 IPOPT 尝试同样的操作 但是 pyoptsparse 没有给出代
  • 使用 NSBezierPath addClip - 如何反转剪辑

    使用 NSBezierPath addClip 仅将绘图限制在用于剪切的路径内部 我想做相反的事情 只在外面画 void drawRect NSRect dirtyRect NSBezierPath dontDrawInThis We wa
  • php中关闭数据库连接的使用

    我总是假设关闭数据库连接始终是一个好习惯 无论数据库 ORM如何 例如 mysql close Propel close 等 参考我的另一篇question https stackoverflow com questions 1236542
  • vue-class-component :调用类方法时出现 TS2339

    我正在使用 vue cli service 构建我的 vuejs 应用程序 构建成功 但在 webstorm IDE 中 我收到一些 TS2339 错误 测试 vue
  • 如何更改 PHP 用于记录到文件的默认时间戳?

    在 php ini 中 error log php errors log So all error log 调用进入文件php errors log 每行前面都有时间戳 例如 17 Jan 2012 18 05 04 是否可以修改该时间戳
  • WPF 窗口中的透明 PNG

    我尝试将具有透明度的 PNG 图像应用到整个窗口 但窗口始终是白色的 有什么线索可以看到 PNG 的透明度吗 谢谢你 C public SplashScreen InitializeComponent var myBrush new Ima
  • 如果默认值不存在则后备背景图像

    我想将图像设置为背景 但图像名称可能是bg png or bg jpg 如果默认背景不存在 是否有任何非 javascript 方法可以创建替代图像的后备 body background url bg png background size
  • C# Json 将任何动态对象转换为键值对

    我正在编写一个工具 它将获取入站 Json 对象 并将其转换为 键值记录 有时可能称为扁平化 目的是避免工具在获取非常大或非常嵌套的 Json 对象时崩溃 因此我想避免递归 一个示例对象可能像这样 如下 包含嵌套数组 空值 你能想到的任何合
  • 在wxPHP中更新属性时如何刷新wxAuiManager窗格?

    我设置了一个简单的wxAuiManager系统包含八个文本控件 每个控件都设置为一个窗格 全部围绕一个中央静态控件排列 我有两个分别捕捉到顶部 左侧 右侧和底部窗格方向 这部分工作正常 我现在想修改每个窗格的属性 我认为可以通过重置关联的来
  • 使用 Fetch API 递归返回分页输出

    Summary 我想使用 JavaScript 的 Fetch API 递归地将分页输出整理到数组中 从 Promise 开始 我认为 async await 函数会更合适 Attempt 这是我的方法 global fetch requi
  • 为什么 Windows 上的 strftime() 返回 false? (我没有使用%e)

    这是我的代码 var dump strftime m d Y l M S time echo br var dump strftime Y d m H M S time 第一行返回 false 第三行返回预期的字符串 2012 10 09
  • 计算 NYSE 交易日的函数

    希望有人可以提供一个给定日期的函数 它将返回纽约证券交易所当月的交易日 如果考虑到假期 那就是额外的好处 如果没有 我也不太担心 提前致谢 我的个人包中有一个函数 名为TradingDates使用假期的 日历从timeDate http c