使用 tq_transmute() 函数时如何保留所有列?

问题描述

我正在尝试在 R 中复制交易策略和回测。但是,我在使用 tq_transmute() 函数时遇到了一个小问题。任何帮助将不胜感激。

所以,到目前为止,我已经编写了以下代码

       #Importing the etfs data
        symbols<- c("SPY","XLF","XLE")
        start<-as.Date("2000-01-01")
        end<- as.Date("2018-12-31")
        
        price_data<- lapply(symbols,function(symbol){
              etfs<-as.data.frame(getSymbols(symbol,src="yahoo",from=start,to= end,auto.assign = FALSE))
              colnames(etfs)<- c("Open","High","Low","Close","volume","Adjusted")
              etfs$Symbol<- symbol
              etfs$Date<- rownames(etfs)
              etfs
            })
    
     # Next,I used do.call() with rbind() to combine the data into a single data frame   
        
        etfs_df<- do.call(rbind,price_data)
    
        #This because of POSIXct error
        daily_price<- etfs_df %>%
                  mutate(Date=as.Date(Date,frac=1)) 
# I have deleted some columns of the table as my work only concerned the "Adjusted" column. 
#So,until Now we have:
 
        head(daily_price)
    
          Adjusted Symbol       Date
        1 98.14607    SPY 2000-01-03
        2 94.30798    SPY 2000-01-04
        3 94.47669    SPY 2000-01-05
        4 92.95834    SPY 2000-01-06
        5 98.35699    SPY 2000-01-07
        6 98.69440    SPY 2000-01-10
    
        #Converting the daily adjusted price to monthly adjusted price
    
        monthly_price<- 
      tq_transmute(daily_price,select = Adjusted,mutate_fun = to.monthly,indexAt = "lastof")
    
    head(monthly_price)
    
    # And Now,I get the following table: 
    
    # A tibble: 6 x 2
      Date       Adjusted
      <date>        <dbl>
    1 2000-01-31     16.6
    2 2000-02-29     15.9
    3 2000-03-31     17.9
    4 2000-04-30     17.7
    5 2000-05-31     19.7
    6 2000-06-30     18.6

因此,如您所见,日期和调整后的价格已成功转换为月度数字,但我的符号栏消失了。谁能告诉我为什么会发生这种情况,我该如何恢复?

谢谢。

解决方法

Symbol 对数据进行分组并应用 tq_transmute

library(dplyr)
library(quantmod)
library(tidyquant)

monthly_price <- daily_price %>%
                  group_by(Symbol) %>%
                  tq_transmute(daily_price,select = Adjusted,mutate_fun = to.monthly,indexAt = "lastof")

#  Symbol Date       Adjusted
#   <chr>  <date>        <dbl>
# 1 SPY    2000-01-31     94.2
# 2 SPY    2000-02-29     92.7
# 3 SPY    2000-03-31    102. 
# 4 SPY    2000-04-30     98.2
# 5 SPY    2000-05-31     96.6
# 6 SPY    2000-06-30     98.5
# 7 SPY    2000-07-31     97.0
# 8 SPY    2000-08-31    103. 
# 9 SPY    2000-09-30     97.6
#10 SPY    2000-10-31     97.2
# … with 674 more rows

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...