twn39 / code

:memo: 代码笔记,通过 issue 的方式记录日常遇到的问题和学习笔记
13 stars 1 forks source link

R使用httr请求数据 #200

Open twn39 opened 6 years ago

twn39 commented 6 years ago

httr封装了curl,使用比较简单

body <- list(method='get_k_data', jsonrpc='2.0', params=list(code='000651'), id=0)
response <- POST("localhost:4000", add_headers('Content-Type'='application/json'), body=body, encode = "json", verbose())

查看http信息

headers(response)
cookies(response)
content(response)

转换数据为时间序列:

alldata <- as.xts(data[, -1], order.by = as.Date(data$date, format = '%Y-%m-%d'))
twn39 commented 6 years ago

通过RPC获取数据并画图:

#! /usr/bin/env Rscript

library('getopt')

#get options, using the spec as defined by the enclosed list.
#we read the options from the default: commandArgs(TRUE).
spec = matrix(c(
  'code', 'c', 1, "character",
  'from', 'f', 1, "character",
  'to', 't', 1, "character",
  'help', 'h', 0, "logical"

), byrow=TRUE, ncol=4)

opt = getopt(spec)

# if help was asked for print a friendly message 
# and exit with a non-zero error code
if ( !is.null(opt$help) ) {
  cat(getopt(spec, usage=TRUE))
  q(status=1)
}

library("xts")
library("zoo")
library("TTR")
library("quantmod")
library("jsonlite")
library('httr')

getDataFromRPC <- function(code, start, end) {
  body <- list(method='get_k_data', jsonrpc='2.0', params=list(code=code, start=start, end=end), id=0)
  response <- POST("localhost:4000", add_headers('Content-Type'='application/json'), body=body, encode = "json")
  data <- fromJSON(content(response)$result)
  result <- as.xts(data[, -1], order.by=as.Date(data$date, format='%Y-%m-%d'))
  return(result)
}

png(paste('./', opt$code, opt$from, opt$to, '.png'), width = 2300, height=1060)
# data = getSymbols(opt$code, from=opt$from, to=opt$to, auto.assign=FALSE)

data <- getDataFromRPC(opt$code, opt$from, opt$to)
chartSeries(data)
addBBands()
addMACD()
addRSI()
dev.off()
twn39 commented 6 years ago

000001 2017-12-01 2018-07-09