添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
用来从网易财经网获取沪深两市股票日度行情数据。
真的学习了
  1. # cntrade R语言版
  2. # 作者:陈堰平(新华指数有限责任公司,[email protected]
  3. # 使用网易股票数据接口 原stata版的作者为:
  4. # 李春涛(中南财经政法大学,[email protected]
  5. # 张璇(中南财经政法大学,[email protected]
  6. # example:
  7. # cntrade(c('600000', '000008'), path ='D:/stockprice', start = 20010104, end = 20120124)

  8. cntrade <- function(tickers, path = "", start = 19910101, end = "") {

  9. address <- "http://quotes.money.163.com/service/chddata.html"
  10. field <- "&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP"

  11. if (path == "") {
  12. path <- getwd()
  13. }

  14. if (!file.exists(path)) {
  15. dir.create(path)
  16. }

  17. if (substr(path, nchar(path), nchar(path)) != "/") {
  18. path <- paste(path, "/", sep = "")
  19. }

  20. if (end == "") {
  21. year <- substr(Sys.time(), 1, 4)
  22. month <- substr(Sys.time(), 6, 7)
  23. day <- substr(Sys.time(), 9, 10)
  24. end <- paste(year, month, day, sep = "")
  25. }

  26. count <- 0
  27. tickers <- as.character(tickers)
  28. for (name in tickers) {
  29. while (nchar(name) < 6) {
  30. name <- paste("0", name, sep = "")
  31. }

  32. if (nchar(name) > 6) {
  33. warning(paste("invalid stock code: ", name, sep = ""))
  34. next
  35. }

  36. if (as.numeric(name) > 600000) {
  37. url <- paste(address, "?code=0", name, "&start=", start, "&end=", end, field, sep = "")
  38. } else {
  39. url <- paste(address, "?code=1", name, "&start=", start, "&end=", end, field, sep = "")
  40. }
  41. destfile <- paste(path, name, ".csv", sep = "")
  42. download.file(url, destfile, quiet = TRUE)
  43. count <- count + 1
  44. }

  45. if (count == 0) {
  46. cat("一个数据文件都没下载下来!\n")
  47. } else {
  48. cat("数据下载完成!\n")
  49. cat(paste("共下载", count, "个文件\n", sep = ""))
  50. }
  51. }

复制代码
调用举例
  1. cntrade(c(600000, 000001, 600810))
  2. cntrade('000002', start = 19990101)
  3. cntrade(000002, end = 19990101)
  4. cntrade(c(2, 16))

复制代码
转自 http://yanping.me/cn/blog/2013/02/10/cntrade-r-version/