簡體   English   中英

如何使用 tq_transmute() 將一列添加到 tibble 中?

[英]How to add a column into a tibble using tq_transmute()?

我有以下 R 腳本,我用它來檢索所有美國股票的符號並計算它們在一段時間內的回報:

library(dplyr)
library(tidyverse)
library(tidyquant)

symbols <- stockSymbols(exchange = c("AMEX", "NASDAQ", "NYSE"), sort.by = c("Exchange","Symbol"), quiet = FALSE)

symbol_array = symbols$Symbol[c(0:5)]

start_date <- as.Date("2019-03-11")
end_date <- as.Date("2020-03-13")

stock_price_data = tq_get(symbol_array, from = start_date, to = end_date, get = "stock.prices")

stock_returns_data = stock_price_data %>%
  group_by(symbol) %>%
  tq_transmute(select = adjusted,
               mutate_fun = periodReturn,
               period = 'yearly',
               col_rename = 'returns')

stock_returns_data

這個腳本的輸出是:

# A tibble: 10 x 3
# Groups:   symbol [5]
   symbol date        returns
   <chr>  <date>        <dbl>
 1 AAMC   2019-12-31 -0.645  
 2 AAMC   2020-03-12  0.415  
 3 AAU    2019-12-31 -0.0167 
 4 AAU    2020-03-12 -0.508  
 5 ACU    2019-12-31  0.436  
 6 ACU    2020-03-12 -0.108  
 7 ACY    2019-12-31 -0.633  
 8 ACY    2020-03-12 -0.298  
 9 AE     2019-12-31  0.00138
10 AE     2020-03-12 -0.371 

stockSymbols() 函數返回以下內容:

  Symbol                             Name LastSale MarketCap IPOyear           Sector                        Industry Exchange
1   AAMC Altisource Asset Management Corp  15.9300   $25.79M      NA          Finance                     Real Estate     AMEX
2    AAU           Almaden Minerals, Ltd.   0.2801   $31.29M    2015 Basic Industries                 Precious Metals     AMEX
3    ACU         Acme United Corporation.  21.6600   $72.61M    1988    Capital Goods Industrial Machinery/Components     AMEX
4    ACY                AeroCentury Corp.   2.8259    $4.37M      NA       Technology Diversified Commercial Services     AMEX
5     AE   Adams Resources & Energy, Inc.  23.0000   $97.42M      NA           Energy          Oil Refining/Marketing     AMEX

問題:是否可以在返回數據的輸出中包含“部門”?

例如:

# A tibble: 10 x 3
# Groups:   symbol [5]
   symbol date        returns  sector
   <chr>  <date>        <dbl>  <char>
 1 AAMC   2019-12-31 -0.645    Finance
 2 AAMC   2020-03-12  0.415    Finance
 3 AAU    2019-12-31 -0.0167   Basic Industries
 4 AAU    2020-03-12 -0.508    Basic Industries
 5 ACU    2019-12-31  0.436    Capital Goods
 6 ACU    2020-03-12 -0.108    Capital Goods
 7 ACY    2019-12-31 -0.633    Technology
 8 ACY    2020-03-12 -0.298    Technology
 9 AE     2019-12-31  0.00138  Energy
10 AE     2020-03-12 -0.371    Energy

提前致謝!

一種選擇是在left_join “符號”中select相關列后與“符號”數據集進行left_join

library(dplyr)
left_join(stock_returns_data, symbols %>%
                                select(symbol = Symbol, Sector))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM