2 min read

tidyquant 使用技巧

tidyquant的整合程度和便捷程度,有望称为下一个dplyr。 这里的函数思维主要参考 Dancho (2017)

knitr::opts_chunk$set(warning = FALSE, message = FALSE,eval = F)
library(tidyquant)
library(formattable)

tq_get获取数据

stock_data <- 
  c("PPDF","YRD","QD","JT") %>% 
  tq_get(get = "stock.prices",
         from = "2018-01-01",
         to = "2018-05-21")

eda

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_tqscale_color_tq就是为了好看。

tq_transmute周期性表现

stock_data %>% 
  group_by(symbol) %>% 
  tq_transmute(
    select = adjusted,
    mutate_fun = to.period,
    period = "months"
  )

tq_mutate批量产生lags

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

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
  )

其他可用函数

tq_transmute_fun_options()

Dancho, Matt. 2017. “Demo Week: Class(Monday) <- Tidyquant.” 2017. http://www.business-science.io/code-tools/2017/10/23/demo_week_tidyquant.html.