R语言版的cntrade措施
李春涛和张璇两位老师写了个名叫cntrade的stata措施,用来从网易财经网获取沪深两市股票日度行情数据。
我用R重写了这个措施,请看:
# cntrade R语言版
# 作者:陈堰平(统计之都,[email protected])
# 利用网易股票数据接口 原stata版的作者为:
# 李春涛(中南财经政法大学,[email protected])
# 张璇(中南财经政法大学,[email protected])
# example:
# cntrade(c('600000', '000008'), path ='D:/stockprice', start = 20010104, end = 20120124)
cntrade <- function(tickers, path = "", start = 19910101, end = "") {
address <- "http://quotes.money.163.com/service/chddata.html"
field <- "&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP"
if (path == "") {
path <- getwd()
}
if (!file.exists(path)) {
dir.create(path)
}
if (substr(path, nchar(path), nchar(path)) != "/") {
path <- paste(path, "/", sep = "")
}
if (end == "") {
year <- substr(Sys.time(), 1, 4)
month <- substr(Sys.time(), 6, 7)
day <- substr(Sys.time(), 9, 10)
end <- paste(year, month, day, sep = "")
}
count <- 0
tickers <- as.character(tickers)
for (name in tickers) {
while (nchar(name) < 6) {
name <- paste("0", name, sep = "")
}
if (nchar(name) > 6) {
warning(paste("invalid stock code: ", name, sep = ""))
next
}
if (as.numeric(name) > 600000) {
url <- paste(address, "?code=0", name, "&start=", start, "&end=", end, field, sep = "")
} else {
url <- paste(address, "?code=1", name, "&start=", start, "&end=", end, field, sep = "")
}
destfile <- paste(path, name, ".csv", sep = "")
download.file(url, destfile, quiet = TRUE)
count <- count + 1
}
if (count == 0) {
cat("一个数据文件都没下载下来!\n")
} else {
cat("数据下载完成!\n")
cat(paste("共下载", count, "个文件\n", sep = ""))
}
}
挪用举例
cntrade(c('600000', '000001', '600810'), path = "d:\temp", start = 19990101, end = 20121231)
cntrade(c(600000, 000001, 600810))
cntrade('000002', start = 19990101)
cntrade(000002, end = 19990101)
cntrade(c(2, 16))
stata版的先容请看http://blog.sina.com.cn/s/blog_6af14ae20101ggnz.html