R 使用 httr 请求数据

发布于 2023-11-12 20:30:03 字数 2086 浏览 71 评论 0

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'))

通过 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()

000001 2017-12-01 2018-07-09

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

站稳脚跟

暂无简介

文章
评论
29 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文