如何最简验证美国股票交易所当日是否开市?偏好Ruby实现
嘿,我刚好有几个不用手动解析纳斯达克假日日历的简便方案,完美匹配你的需求,分Ruby和shell两种方式给你:
方法一:Shell + curl 快速查询(支持当日/指定日期)
这个方法直接借助搜索引擎的结果,完全不用自己维护假日列表,步骤超简单:
- 检查当日是否开市(输出true/false):
curl -s "https://www.google.com/search?q=Is+NYSE+open+today" | grep -q "Yes, the New York Stock Exchange is open today" && echo "true" || echo "false"
- 检查指定日期(比如2024-12-25):
TARGET_DATE="2024-12-25" curl -s "https://www.google.com/search?q=Is+NYSE+open+on+$TARGET_DATE" | grep -q "Yes, the New York Stock Exchange is open on" && echo "true" || echo "false"
如果想要更友好的输出(比如直接显示“开市”/“闭市”),可以把最后一句改成:
... && echo "开市" || echo "闭市"
方法二:Ruby 实现(轻量无依赖/精准解析)
如果优先用Ruby,这里有两种写法,都不用自己解析日历:
1. 无外部依赖版本(用Ruby原生库)
不用装任何gem,直接用Net::HTTP调用搜索结果:
require 'net/http' require 'uri' require 'date' def nyse_open?(target_date = nil) # 构造查询语句 query = if target_date "Is NYSE open on #{target_date.strftime('%Y-%m-%d')}" else "Is NYSE open today" end # 编码URL并发起请求 encoded_url = URI.encode("https://www.google.com/search?q=#{query}") response = Net::HTTP.get(URI(encoded_url)) # 判断结果,返回布尔值 response.include?("Yes, the New York Stock Exchange is open") end # 调用示例 # 检查当日 puts nyse_open? ? "true" : "false" # 检查2024年感恩节次日(11月29日) puts nyse_open?(Date.new(2024, 11, 29)) ? "true" : "false"
2. 精准解析版本(用Nokogiri提取结果)
如果觉得字符串匹配不够精准,可以用nokogiri来提取搜索引擎的结构化结果,先安装依赖:
gem install nokogiri
然后脚本写成:
require 'net/http' require 'uri' require 'date' require 'nokogiri' def nyse_open?(target_date = nil) query = target_date ? "Is NYSE open on #{target_date.strftime('%Y-%m-%d')}" : "Is NYSE open today" encoded_url = URI.encode("https://www.google.com/search?q=#{query}") html = Net::HTTP.get(URI(encoded_url)) doc = Nokogiri::HTML(html) # 提取搜索结果的核心回答文本 result_text = doc.at_css('.Z0LcW')&.text || "" result_text.start_with?("Yes") end # 调用方式和上面一致
额外:获取距下一次开市的时间
如果想要获取距离下一次开市的时长,建议用免费的金融数据API(专门提供美股交易时间的类型),这类API会直接返回结构化的开市/闭市时间,你可以用Ruby的Time类计算倒计时,或者用shell脚本结合date命令处理,不用自己解析复杂的假日规则。
内容的提问来源于stack exchange,提问作者Marcos
相关产品推荐
相关产品推荐

