Install TidyQuant

install.packages('tidyquant', repos = "http://cran.us.r-project.org")
## Installing package into 'C:/Users/Gen Shiraishi/AppData/Local/R/win-library/4.2'
## (as 'lib' is unspecified)
## package 'tidyquant' successfully unpacked and MD5 sums checked
## 
## The downloaded binary packages are in
##  C:\Users\Gen Shiraishi\AppData\Local\Temp\Rtmp6vpzK3\downloaded_packages

Load TidyQuant and dplyr

library(tidyquant)
## Loading required package: lubridate
## 
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
## Loading required package: PerformanceAnalytics
## Loading required package: xts
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## 
## Attaching package: 'PerformanceAnalytics'
## The following object is masked from 'package:graphics':
## 
##     legend
## Loading required package: quantmod
## Loading required package: TTR
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:xts':
## 
##     first, last
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union

Get historical Apple stock prices

tq_get("AAPL", get = "stock.prices")
## # A tibble: 2,712 × 8
##    symbol date        open  high   low close    volume adjusted
##    <chr>  <date>     <dbl> <dbl> <dbl> <dbl>     <dbl>    <dbl>
##  1 AAPL   2012-01-03  14.6  14.7  14.6  14.7 302220800     12.5
##  2 AAPL   2012-01-04  14.6  14.8  14.6  14.8 260022000     12.6
##  3 AAPL   2012-01-05  14.8  14.9  14.7  14.9 271269600     12.7
##  4 AAPL   2012-01-06  15.0  15.1  15.0  15.1 318292800     12.9
##  5 AAPL   2012-01-09  15.2  15.3  15.0  15.1 394024400     12.9
##  6 AAPL   2012-01-10  15.2  15.2  15.1  15.1 258196400     12.9
##  7 AAPL   2012-01-11  15.1  15.1  15.0  15.1 215084800     12.9
##  8 AAPL   2012-01-12  15.1  15.1  15.0  15.0 212587200     12.8
##  9 AAPL   2012-01-13  15.0  15.0  15.0  15.0 226021600     12.8
## 10 AAPL   2012-01-17  15.2  15.2  15.1  15.2 242897200     13.0
## # … with 2,702 more rows

Get historical S&P 500 stock prices

sp_500 <- tq_index("SP500") %>%
  tq_get(get = "stock.prices")
## Getting holdings for SP500
sp_500
## # A tibble: 1,324,671 × 15
##    symbol company   ident…¹ sedol weight sector share…² local…³ date        open
##    <chr>  <chr>     <chr>   <chr>  <dbl> <chr>    <dbl> <chr>   <date>     <dbl>
##  1 AAPL   Apple In… 037833… 2046… 0.0696 Infor…  1.64e8 USD     2012-01-03  14.6
##  2 AAPL   Apple In… 037833… 2046… 0.0696 Infor…  1.64e8 USD     2012-01-04  14.6
##  3 AAPL   Apple In… 037833… 2046… 0.0696 Infor…  1.64e8 USD     2012-01-05  14.8
##  4 AAPL   Apple In… 037833… 2046… 0.0696 Infor…  1.64e8 USD     2012-01-06  15.0
##  5 AAPL   Apple In… 037833… 2046… 0.0696 Infor…  1.64e8 USD     2012-01-09  15.2
##  6 AAPL   Apple In… 037833… 2046… 0.0696 Infor…  1.64e8 USD     2012-01-10  15.2
##  7 AAPL   Apple In… 037833… 2046… 0.0696 Infor…  1.64e8 USD     2012-01-11  15.1
##  8 AAPL   Apple In… 037833… 2046… 0.0696 Infor…  1.64e8 USD     2012-01-12  15.1
##  9 AAPL   Apple In… 037833… 2046… 0.0696 Infor…  1.64e8 USD     2012-01-13  15.0
## 10 AAPL   Apple In… 037833… 2046… 0.0696 Infor…  1.64e8 USD     2012-01-17  15.2
## # … with 1,324,661 more rows, 5 more variables: high <dbl>, low <dbl>,
## #   close <dbl>, volume <dbl>, adjusted <dbl>, and abbreviated variable names
## #   ¹​identifier, ²​shares_held, ³​local_currency

View tq transmute options

tq_transmute_fun_options()
## $zoo
##  [1] "rollapply"          "rollapplyr"         "rollmax"           
##  [4] "rollmax.default"    "rollmaxr"           "rollmean"          
##  [7] "rollmean.default"   "rollmeanr"          "rollmedian"        
## [10] "rollmedian.default" "rollmedianr"        "rollsum"           
## [13] "rollsum.default"    "rollsumr"          
## 
## $xts
##  [1] "apply.daily"     "apply.monthly"   "apply.quarterly" "apply.weekly"   
##  [5] "apply.yearly"    "diff.xts"        "lag.xts"         "period.apply"   
##  [9] "period.max"      "period.min"      "period.prod"     "period.sum"     
## [13] "periodicity"     "to.daily"        "to.hourly"       "to.minutes"     
## [17] "to.minutes10"    "to.minutes15"    "to.minutes3"     "to.minutes30"   
## [21] "to.minutes5"     "to.monthly"      "to.period"       "to.quarterly"   
## [25] "to.weekly"       "to.yearly"       "to_period"      
## 
## $quantmod
##  [1] "allReturns"      "annualReturn"    "ClCl"            "dailyReturn"    
##  [5] "Delt"            "HiCl"            "Lag"             "LoCl"           
##  [9] "LoHi"            "monthlyReturn"   "Next"            "OpCl"           
## [13] "OpHi"            "OpLo"            "OpOp"            "periodReturn"   
## [17] "quarterlyReturn" "seriesAccel"     "seriesDecel"     "seriesDecr"     
## [21] "seriesHi"        "seriesIncr"      "seriesLo"        "weeklyReturn"   
## [25] "yearlyReturn"   
## 
## $TTR
##  [1] "adjRatios"          "ADX"                "ALMA"              
##  [4] "aroon"              "ATR"                "BBands"            
##  [7] "CCI"                "chaikinAD"          "chaikinVolatility" 
## [10] "CLV"                "CMF"                "CMO"               
## [13] "CTI"                "DEMA"               "DonchianChannel"   
## [16] "DPO"                "DVI"                "EMA"               
## [19] "EMV"                "EVWMA"              "GMMA"              
## [22] "growth"             "HMA"                "keltnerChannels"   
## [25] "KST"                "lags"               "MACD"              
## [28] "MFI"                "momentum"           "OBV"               
## [31] "PBands"             "ROC"                "rollSFM"           
## [34] "RSI"                "runCor"             "runCov"            
## [37] "runMAD"             "runMax"             "runMean"           
## [40] "runMedian"          "runMin"             "runPercentRank"    
## [43] "runSD"              "runSum"             "runVar"            
## [46] "SAR"                "SMA"                "SMI"               
## [49] "SNR"                "stoch"              "TDI"               
## [52] "TRIX"               "ultimateOscillator" "VHF"               
## [55] "VMA"                "volatility"         "VWAP"              
## [58] "VWMA"               "wilderSum"          "williamsAD"        
## [61] "WMA"                "WPR"                "ZigZag"            
## [64] "ZLEMA"             
## 
## $PerformanceAnalytics
## [1] "Return.annualized"        "Return.annualized.excess"
## [3] "Return.clean"             "Return.cumulative"       
## [5] "Return.excess"            "Return.Geltner"          
## [7] "zerofill"

Convert historical S&P stock prices to monthly returns

sp_500 %>%
  group_by(symbol) %>%
  tq_transmute(adjusted, mutate_fun = monthlyReturn)
## # A tibble: 63,526 × 3
## # Groups:   symbol [504]
##    symbol date       monthly.returns
##    <chr>  <date>               <dbl>
##  1 AAPL   2012-01-31         0.110  
##  2 AAPL   2012-02-29         0.188  
##  3 AAPL   2012-03-30         0.105  
##  4 AAPL   2012-04-30        -0.0260 
##  5 AAPL   2012-05-31        -0.0107 
##  6 AAPL   2012-06-29         0.0109 
##  7 AAPL   2012-07-31         0.0458 
##  8 AAPL   2012-08-31         0.0939 
##  9 AAPL   2012-09-28         0.00280
## 10 AAPL   2012-10-31        -0.108  
## # … with 63,516 more rows