基于R语言的印度NSE交易所EOD股票数据下载技术问询
Hey there! As someone who’s tinkered with R for Indian stock market data, I totally get your frustration with Quandl and quantmod when it comes to reliable daily EOD pulls. Let’s walk through a solid solution to grab NSE’s official bhav copy files directly in R—this should fix your daily data needs.
第一步:准备必要的R包
You’ll need a few packages to handle HTTP requests, read CSV files efficiently, and manage dates. Install and load them first:
# 安装依赖包(首次使用时运行) install.packages(c("httr", "data.table", "lubridate")) # 加载包 library(httr) library(data.table) library(lubridate)
第二步:手动获取指定日期的Bhav Copy
Taking your example of April 30th, here’s how to download and read the corresponding bhav copy:
# 构建目标日期的bhav copy链接(NSE的链接格式固定,日期为DDMMMYYYY大写格式) bhav_url <- "https://www.nseindia.com/content/historical/EQUITIES/2024/APR/cm30APR2024bhav.csv.zip" # 下载ZIP文件到临时目录 temp_zip <- tempfile(fileext = ".zip") GET(bhav_url, write_disk(temp_zip)) # 解压并读取CSV数据 unzip(temp_zip, exdir = tempdir()) csv_path <- list.files(tempdir(), pattern = "\\.csv$", full.names = TRUE) eod_data <- fread(csv_path) # 查看数据结构确认结果 str(eod_data)
第三步:自动生成日期链接(进阶批量获取)
If you need to pull data for multiple dates, wrap the logic in a reusable function to auto-generate valid URLs:
get_nse_bhav <- function(target_date) { # 转换日期为NSE要求的格式:DDMMMYYYY(大写) date_formatted <- toupper(format(target_date, "%d%b%Y")) year <- format(target_date, "%Y") month <- toupper(format(target_date, "%b")) # 拼接完整链接 bhav_url <- paste0( "https://www.nseindia.com/content/historical/EQUITIES/", year, "/", month, "/cm", date_formatted, "bhav.csv.zip" ) # 下载、解压、读取数据 temp_zip <- tempfile(fileext = ".zip") GET(bhav_url, write_disk(temp_zip), add_headers("User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36")) unzip(temp_zip, exdir = tempdir()) csv_path <- list.files(tempdir(), pattern = "\\.csv$", full.names = TRUE) eod_data <- fread(csv_path) return(eod_data) } # 示例:获取2024年4月30日的数据 apr30_data <- get_nse_bhav(ymd("2024-04-30")) head(apr30_data)
关键注意事项
- NSE publishes bhav copies only on trading days, usually after 6 PM IST. Non-trading days will have no available file.
- If you hit HTTP errors, adding a user-agent header (like in the function above) helps bypass NSE’s basic anti-scraping checks.
- To filter for specific stocks, use the
SYMBOLcolumn:# 提取RELIANCE的当日收盘价 reliance_close <- apr30_data[SYMBOL == "RELIANCE", .(SYMBOL, CLOSE)]
This method gives you direct access to NSE’s official EOD data, so it’s far more reliable than third-party tools for daily updates.
内容的提问来源于stack exchange,提问作者AKshayKulkarni

