library(tidyquant)
library(tidyverse)

# Import data
from = today() - years(4)
Stocks <- tq_get("TSLA", get = "stock.prices", from = from)
Stocks
## # A tibble: 1,006 x 7
##    date        open  high   low close  volume adjusted
##    <date>     <dbl> <dbl> <dbl> <dbl>   <dbl>    <dbl>
##  1 2015-03-05  203.  206.  200.  201. 4877000     201.
##  2 2015-03-06  199.  201.  192.  194. 6712400     194.
##  3 2015-03-09  194.  194.  188.  191. 6736700     191.
##  4 2015-03-10  188.  194.  188.  190. 5530900     190.
##  5 2015-03-11  191.  196.  191.  194. 4974900     194.
##  6 2015-03-12  194.  194.  190.  191. 4149300     191.
##  7 2015-03-13  189.  192.  187.  189. 5434300     189.
##  8 2015-03-16  192   196.  190.  196. 5628800     196.
##  9 2015-03-17  195.  199.  194.  195. 4883200     195.
## 10 2015-03-18  195.  201.  193.  201. 4756300     201.
## # … with 996 more rows
# See the list of different mutate_fun avaiable 
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"
##  [4] "apply.weekly"    "apply.yearly"    "diff.xts"       
##  [7] "lag.xts"         "period.apply"    "period.max"     
## [10] "period.min"      "period.prod"     "period.sum"     
## [13] "periodicity"     "to_period"       "to.daily"       
## [16] "to.hourly"       "to.minutes"      "to.minutes10"   
## [19] "to.minutes15"    "to.minutes3"     "to.minutes30"   
## [22] "to.minutes5"     "to.monthly"      "to.period"      
## [25] "to.quarterly"    "to.weekly"       "to.yearly"      
## 
## $quantmod
##  [1] "allReturns"      "annualReturn"    "ClCl"           
##  [4] "dailyReturn"     "Delt"            "HiCl"           
##  [7] "Lag"             "LoCl"            "LoHi"           
## [10] "monthlyReturn"   "Next"            "OpCl"           
## [13] "OpHi"            "OpLo"            "OpOp"           
## [16] "periodReturn"    "quarterlyReturn" "seriesAccel"    
## [19] "seriesDecel"     "seriesDecr"      "seriesHi"       
## [22] "seriesIncr"      "seriesLo"        "weeklyReturn"   
## [25] "yearlyReturn"   
## 
## $TTR
##  [1] "adjRatios"          "ADX"                "ALMA"              
##  [4] "aroon"              "ATR"                "BBands"            
##  [7] "CCI"                "chaikinAD"          "chaikinVolatility" 
## [10] "CLV"                "CMF"                "CMO"               
## [13] "DEMA"               "DonchianChannel"    "DPO"               
## [16] "DVI"                "EMA"                "EMV"               
## [19] "EVWMA"              "GMMA"               "growth"            
## [22] "HMA"                "KST"                "lags"              
## [25] "MACD"               "MFI"                "momentum"          
## [28] "OBV"                "PBands"             "ROC"               
## [31] "rollSFM"            "RSI"                "runCor"            
## [34] "runCov"             "runMAD"             "runMax"            
## [37] "runMean"            "runMedian"          "runMin"            
## [40] "runPercentRank"     "runSD"              "runSum"            
## [43] "runVar"             "SAR"                "SMA"               
## [46] "SMI"                "SNR"                "stoch"             
## [49] "TDI"                "TRIX"               "ultimateOscillator"
## [52] "VHF"                "VMA"                "volatility"        
## [55] "VWAP"               "VWMA"               "wilderSum"         
## [58] "williamsAD"         "WMA"                "WPR"               
## [61] "ZigZag"             "ZLEMA"             
## 
## $PerformanceAnalytics
## [1] "Return.annualized"        "Return.annualized.excess"
## [3] "Return.clean"             "Return.cumulative"       
## [5] "Return.excess"            "Return.Geltner"          
## [7] "zerofill"

# Calculate daily returns. Do not save the result.
Stocks %>%
    tq_mutate(select = adjusted, mutate_fun = periodReturn, period = "daily") 
## # A tibble: 1,006 x 8
##    date        open  high   low close  volume adjusted daily.returns
##    <date>     <dbl> <dbl> <dbl> <dbl>   <dbl>    <dbl>         <dbl>
##  1 2015-03-05  203.  206.  200.  201. 4877000     201.       0      
##  2 2015-03-06  199.  201.  192.  194. 6712400     194.      -0.0336 
##  3 2015-03-09  194.  194.  188.  191. 6736700     191.      -0.0155 
##  4 2015-03-10  188.  194.  188.  190. 5530900     190.      -0.00293
##  5 2015-03-11  191.  196.  191.  194. 4974900     194.       0.0180 
##  6 2015-03-12  194.  194.  190.  191. 4149300     191.      -0.0138 
##  7 2015-03-13  189.  192.  187.  189. 5434300     189.      -0.0125 
##  8 2015-03-16  192   196.  190.  196. 5628800     196.       0.0372 
##  9 2015-03-17  195.  199.  194.  195. 4883200     195.      -0.00496
## 10 2015-03-18  195.  201.  193.  201. 4756300     201.       0.0307 
## # … with 996 more rows

Q1 Import stock prices of Facebook and Apple for the last 5 years.

Hint: Add group_by(symbol) at the end of the code so that calculations below will be done per stock.

# Import data
from = today() - years(5)
Stocks <- tq_get(c("FB","AAPL"), get = "stock.prices", from = from) %>%
group_by(symbol)
Stocks
## # A tibble: 2,516 x 8
## # Groups:   symbol [2]
##    symbol date        open  high   low close   volume adjusted
##    <chr>  <date>     <dbl> <dbl> <dbl> <dbl>    <dbl>    <dbl>
##  1 FB     2014-03-05  69.7  72.0  69.6  71.6 74567700     71.6
##  2 FB     2014-03-06  71.9  71.9  70.2  70.8 46026500     70.8
##  3 FB     2014-03-07  71.1  71.2  69.5  69.8 38927000     69.8
##  4 FB     2014-03-10  70.8  72.2  70.5  72.0 59871600     72.0
##  5 FB     2014-03-11  72.5  72.6  70.0  70.1 59408300     70.1
##  6 FB     2014-03-12  69.9  71.3  69    70.9 46340500     70.9
##  7 FB     2014-03-13  71.3  71.3  68.2  68.8 57091000     68.8
##  8 FB     2014-03-14  68.5  69.4  67.5  67.7 48227000     67.7
##  9 FB     2014-03-17  68.2  68.9  66.6  68.7 52197000     68.7
## 10 FB     2014-03-18  68.8  69.6  68.3  69.2 40827000     69.2
## # … with 2,506 more rows

Q2 Create a line chart for both stocks.

Hint: Use ggplot2::facet_wrap. Refer to the ggplot2 cheatsheet. See the section for Faceting.

Stocks %>% 
  ggplot(aes(x = date, y = adjusted)) + 
  geom_line() +
   facet_wrap(~symbol)

Q3 Calculate quarterly returns, and save the result under returns_quarterly.

Hint: Take the adjusted variable from Stocks, and calculate quarterly returns using tq_transmute(), instead of tq_mutate(), which is used when periodicity changes. Another difference between the two is that tq_transmute() returns only newly-created columns while tq_mutate() adds new columns to existing variables.

Note that there are a variety of functions available with the mutate_fun argument: See above for the result of tq_transmute_fun_options(). Note that tq_mutate allows to calculate returns using quantmod::periodReturn. Google the quantmod package manual for more information on the periodReturn function.

returns_quarterly <-
 Stocks %>%
    tq_transmute(select = adjusted, mutate_fun = periodReturn, period = "quarterly")
    
returns_quarterly
## # A tibble: 42 x 3
## # Groups:   symbol [2]
##    symbol date       quarterly.returns
##    <chr>  <date>                 <dbl>
##  1 FB     2014-03-31          -0.158  
##  2 FB     2014-06-30           0.117  
##  3 FB     2014-09-30           0.175  
##  4 FB     2014-12-31          -0.0129 
##  5 FB     2015-03-31           0.0538 
##  6 FB     2015-06-30           0.0432 
##  7 FB     2015-09-30           0.0482 
##  8 FB     2015-12-31           0.164  
##  9 FB     2016-03-31           0.0902 
## 10 FB     2016-06-30           0.00158
## # … with 32 more rows

Q4 Create a density plot for returns of both stocks.

Hint: Refer to the ggplot2 cheatsheet. Look for geom_density under One Variable. Use the fill argument to create the plot per each stock.

returns_quarterly %>%
  ggplot(aes(x=quarterly.returns, fill= symbol)) +
  geom_density(alpha = 0.3)

Q5 Which of the two stocks would you expect the most stable returns quarter after quarter without worrying too much of fluctutations?

Hint: Examine the density plot. Note that density is mapped to the vertical axis, while return percentage is to the horizontal axis. The thinner and taller the distribution is, the smaller the range of possible return percentages are. The thicker and shorter the distribution is, the wider the range of possible return percentages are. Hence, it would be more difficult to make predictions for a thicker and shorter distribution than for a thinner and taller one.

Apple because it is taller and thinner.

Q6 Which of the two stocks would you expect the most frequent large negative returns?

Hint: As was described in Q3 hint, returns are mapped to the horizontal axis with negative returns on the left while negative returns on the right. Thus, the distribution that is skewed to the far left suggests the possibility of large negative returns (a negative skewness). In addition, the thicker tail on the left is indicative of the larger probability of negative returns.

Density is the frequency, Apple has a larger negative return because it happened more freqently and they have a larger tail going to the left. The larger tail on the left the more negative frequency.