安裝Tushare
打開RStudio,在控制臺輸入命令:
> install.packages('Tushare')
Tushare的R包需要依賴httr、tidyverse、forecast和data.table這四個包。
由于Tushare包中申明了依賴關系,因此這四個依賴包也會自動下載下來。如果下載過程卡住了,導致下載失敗,可以重試幾次,畢竟CRAN的服務器不在大陸,后面將介紹如何使用CRAN的國內(nèi)鏡像。
載入Tushare
如同安裝過程,在載入Tushare的同時,R也會自動載入其依賴的包。
> library('Tushare')
也可以通過help查看Tushare的相關信息
> help('Tushare')
在R官網(wǎng)也可以看到Tushare的索引信息:
使用Tushare
獲得api接口對象
> api <- Tushare::pro_api(token = 'YOUR TOKEN HERE')
如同在Python包中使用Tushare Pro的pro.query,向api(只要調(diào)用Tushare::pro_api獲得了接口,你可以使用任意的名字命名)傳遞想要調(diào)用的接口名以及相應的參數(shù)就可以調(diào)用相應的數(shù)據(jù)。
在api中,必須傳遞的是Tushare Pro提供的接口名(詳細請見官方網(wǎng)站https:///),其他參數(shù)視相應的接口傳入相應的參數(shù)。
Tips:Tushare的0.1.1版本的R包暫時不支持fields字段。
示例1:只傳入接口名而不傳入其他參數(shù)調(diào)用api接口
> api(api_name = 'stock_basic')
接下來使用pro_bar文檔中的一個示例來演示傳入接口名和其他參數(shù)調(diào)用api接口。
示例2:傳入接口名和其他參數(shù)調(diào)用api接口
> api(api_name = 'daily', ts_code = "000001.SZ", start_date = "20181001", end_date = "20181010")
pro_bar接口的使用
獲得pro_bar接口,并命名為bar。和Tushare Pro的python包一樣,為了統(tǒng)一使用行情接口,Tushare的R包也提供了pro_bar。
> bar <- Tushare::pro_bar(token = 'YOUR TOKEN HERE')
> bar(ts_code = "000001.SZ", start_date = "20181001", end_date = "20181010")
bar接口可以傳遞adj來同時調(diào)取行情以及復權因子,并將計算后的結果返回出來。其他接口參數(shù)請參考Tushare Pro網(wǎng)站的詳細說明。
> bar(ts_code = "000001.SZ", start_date = "20181001", adj = "hfq", ma = c(5,10))
一個樣例
最后,我們來執(zhí)行一段程序,獲取平安銀行的后復權數(shù)據(jù)并完成可視化展示。
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)
df$id = dim(df)[1]:1
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())
p = ggplot(df, aes(x=id))+
geom_boxplot(aes(lower= candleLower,
middle = candleLower,
upper = candleUpper,
ymin = low,
ymax = high,
color= ifelse(open>close,"green","red"),
width= 0.5),
stat = 'identity',
size = .5)+
scale_color_manual(values = c("green","red"))+
theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
axis.title = element_blank(),
axis.text.x = element_text(angle = 65, hjust = 1),
legend.position="none"
)
p + geom_line(aes(x=id, y=ma5), color="orange", size=.5)+
geom_line(aes(x=id, y=ma10), color="purple", size=.5)+
geom_line(aes(x=id, y=ma20), color="blue", size=.5)












