金融科技选股机器人-tidyquant的使用教学

下载套件

install.packages('tidyquant')

加载套件

library(tidyquant)
library(dplyr)

下载多个股票

stocks <- tq_get(c("AAPL", "MSFT", "GOOG"),
                 from = "2020-01-01",
                 to   = "2024-12-31")

head(stocks)

下载单个股票

aapl <- tq_get("AAPL",
                 from = "2020-01-01",
                 to   = "2024-12-31")

head(aapl)

针对AAPL做对数收益率

returns <- aapl %>%
  tq_transmute(select     = adjusted,     # 选择调整收盘价
               mutate_fun = periodReturn, # 计算收益率
               period     = "daily",      # 日收益率
               type       = "log")        # 对数收益率

head(returns)

针对多个股票做对数收益率

multi_returns <- stocks %>%
  group_by(symbol) %>%
  tq_transmute(select     = adjusted,
               mutate_fun = periodReturn,
               period     = "monthly",
               type       = "log")

head(multi_returns)

绘出各个股票的月收益率的图表

library(ggplot2)

multi_returns %>%
  ggplot(aes(x = date, y = monthly.returns, color = symbol)) +
  geom_line() +
  labs(title = "Monthly Returns",
       y = "Log Returns")

取得单个股票的基本面资讯

aapl_fin <- tq_get("AAPL", get = "financials")
aapl_fin