{r setup, include=FALSE} knitr::opts_chunk$set(eval = FALSE)
tidyquant的整合程度和便捷程度,有望称为下一个dplyr。 这里的函数思维主要参考 @Dancho2017。
tq_get获取数据
{r cache=T} stock_data <- c("PPDF","YRD","QD","JT") %>% tq_get(get = "stock.prices", from = "2018-01-01", to = "2018-05-21")
eda
{r cache=T} stock_data %>% head stock_data %>% ggplot(aes(x = date, y = adjusted, col = symbol)) + geom_line() + facet_wrap(~ symbol, ncol = 2, scales = "free_y") + theme_tq() + scale_color_tq() + labs( title = "四家普惠金融股票股价表现", subtitle = "JT: 融360, PPDF: 拍拍贷, QD: 趣店, TRD: 宜人贷") + theme(text = element_text(family = "STKaiti")) stock_data %>% mutate(mktcap = close * volume, mktcap = accounting(mktcap)) %>% ggplot(aes(x = date, y = mktcap, col = symbol)) + geom_line() + facet_wrap(~ symbol, ncol = 2, scales = "free_y") + theme_tq() + scale_color_tq() + labs( title = "四家普惠金融股票市值表现", subtitle = "JT: 融360, PPDF: 拍拍贷, QD: 趣店, TRD: 宜人贷") + theme(text = element_text(family = "STKaiti"))
theme_tq和scale_color_tq就是为了好看。
tq_transmute周期性表现
{r cache=T} stock_data %>% group_by(symbol) %>% tq_transmute( select = adjusted, mutate_fun = to.period, period = "months )
tq_mutate批量产生lags
{r cache=T} stock_data %>% select(symbol, date, adjusted) %>% group_by(symbol) %>% tq_mutate( select = adjusted, mutate_fun = lag.xts, k = 1:5, col_rename = paste0("adjusted_lag_",1:5) )
tq_mutate滚动产生statistic
{r cache=T} stock_data %>% select(symbol, date, adjusted) %>% group_by(symbol) %>% tq_mutate( select = adjusted, mutate_fun = rollapply, width = 5, by.column = FALSE, FUN = quantile, probs = c(0, 0.025, 0.25, 0.5, 0.75, 0.975, 1), na.rm = T )
其他可用函数
`{r cache=T} tq_transmute_fun_options()