使用R调用Tushare数据

使用R调用Tushare数据

强烈推荐注册Tushare呀,R包接口都出来了,调用数据好方便的!关于Tushare包的介绍参考这篇微信推文:像Python一样方便的用R获取金融数据

安装

首先是安装:

1
install.packages('Tushare')

使用

使用api接口对象

1
2
3
4
5
6
7
8
9
10
11
12
13
## 使用api接口对象
api <- pro_api(token = "ab61372e177846b3d24829738eddde4293a7f25caa53d1df104aa9c1")

# 只传入接口名而不传入其他参数调用api接口
stock_basic <- api(api_name = 'stock_basic')
head(stock_basic)

# 传入接口名和其他参数调用api接口
pingan <- api(api_name = 'daily',
ts_code = '000001.SZ',
start_date = '20180101',
end_date = '20181107')
head(pingan)

使用pro_bar接口

1
2
3
4
5
6
7
8
9
10
bar <- pro_bar(token = "ab61372e177846b3d24829738eddde4293a7f25caa53d1df104aa9c1")
pingan2 <- bar(ts_code = '000001.SZ',
start_date = "20180101",
end_date = "20181107")
head(pingan2)

# bar接口可以传递adj同时调取行情以及复权因子,并将计算结果返回出来
pingan3 <- bar(ts_code = '000001.SZ', start_date = '20180101',
end_date = '20181107', adj = 'hfq', ma = c(5, 10))
head(pingan3)

使用示例:绘制蜡烛图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# 蜡烛图绘制
# 把trade_date变成日期格式
df = bar(ts_code = '000001.SZ', start_date = '20180101', adj = 'hfq',
ma = c(5, 10, 20)) %>%
mutate(trade_date = as.Date(gsub('^(\\d{4})(\\d{2})(\\d{2})',
'\\1-\\2-\\3', trade_date))) %>%
mutate_at(vars(3:dim(.)[2]), as.numeric)
head(df)

df$candleLower = pmin(df$open, df$close)
df$candleUpper = pmax(df$open, df$close)
df$candleMiddle = (df$candleLower + df$candleUpper)/2
theme_set(theme_bw(base_size = 20, base_family = "STSong") +
theme(plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5)))

(p <- ggplot(df, aes(x = trade_date)) +
geom_boxplot(aes(lower = candleLower,
middle = candleMiddle,
upper = candleUpper,
ymin = low,
ymax = high,
color = ifelse(open > close, "#61aa5d", "#fe5e5c"),
width = 0.5),
stat = 'identity',
size = 0.5) +
scale_color_manual(values = c("#61aa5d", "#fe5e5c")) +
theme(legend.position = "none") +
geom_line(aes(x = trade_date, y = ma5), color = "orange", size = 0.5) +
geom_line(aes(x = trade_date, y = ma10), color = "purple", size = 0.5) +
geom_line(aes(x = trade_date, y = ma20), color = 'blue', size = 0.5) +
scale_x_date(labels = scales::date_format()) +
labs(x = "交易日",
y = "股价",
title = "平安银行K线图",
subtitle = '数据来源:Tushare'))

# R

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×

keyboard_arrow_up