Suppose that you are weighing two stocks for investment: Apple and Microsoft. So you want to find out their historical performance in the past. If you had invested $1 in each stock at the beginning of 2000, which of the two stocks would have come out at the top today? What if you want to add another stock to the consideration?
library(tidyquant)
library(ggplot2)
# Pick stocks
stocks <- c("AAPL", "MSFT")
# Import stock prices
stock_prices <- stocks %>%
tq_get(get = "stock.prices",
from = "2001-01-01",
to = Sys.Date()) %>%
group_by(symbol)
stock_prices
## # A tibble: 8,754 x 8
## # Groups: symbol [2]
## symbol date open high low close volume adjusted
## <chr> <date> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 AAPL 2001-01-02 1.06 1.09 1.04 1.06 113078000. 0.717
## 2 AAPL 2001-01-03 1.04 1.19 1.03 1.17 204268400. 0.789
## 3 AAPL 2001-01-04 1.30 1.32 1.20 1.22 184849000. 0.822
## 4 AAPL 2001-01-05 1.21 1.24 1.15 1.17 103089000. 0.789
## 5 AAPL 2001-01-08 1.21 1.21 1.14 1.18 93424800. 0.798
## 6 AAPL 2001-01-09 1.20 1.26 1.18 1.23 147232400. 0.828
## 7 AAPL 2001-01-10 1.19 1.21 1.15 1.18 145195400. 0.798
## 8 AAPL 2001-01-11 1.16 1.32 1.16 1.29 200933600. 0.867
## 9 AAPL 2001-01-12 1.28 1.29 1.22 1.23 105844200. 0.828
## 10 AAPL 2001-01-16 1.25 1.30 1.21 1.22 76529600. 0.825
## # ... with 8,744 more rows
# Chart stock prices using line graph
stock_prices %>%
ggplot(aes(x = date, y = adjusted)) +
geom_line() +
facet_wrap(~symbol)
# Suppose that you invested $1 on the first day of the period.
# Which of the stocks would have come out at the top at the end of the period?
stock_prices %>%
group_by(symbol) %>%
mutate(adjusted = adjusted / adjusted[1]) %>%
ungroup() %>%
ggplot(aes(x = date, y = adjusted, col = symbol)) +
geom_line()
# How much of the one dollar invested on the first day would have grown to at the end?
stock_prices %>%
group_by(symbol) %>%
mutate(adjusted = adjusted / adjusted[1]) %>%
summarise(last = last(adjusted))
## # A tibble: 2 x 2
## symbol last
## <chr> <dbl>
## 1 AAPL 263.
## 2 MSFT 6.20