# Load packages
library(tidyquant)
## Warning: package 'tidyquant' was built under R version 4.0.3
## Warning: package 'lubridate' was built under R version 4.0.3
## Warning: package 'PerformanceAnalytics' was built under R version 4.0.3
## Warning: package 'xts' was built under R version 4.0.3
## Warning: package 'zoo' was built under R version 4.0.3
## Warning: package 'quantmod' was built under R version 4.0.3
## Warning: package 'TTR' was built under R version 4.0.3
library(tidyverse) # for count() function
## Warning: package 'tidyverse' was built under R version 4.0.3
## Warning: package 'ggplot2' was built under R version 4.0.3
## Warning: package 'tibble' was built under R version 4.0.3
## Warning: package 'tidyr' was built under R version 4.0.3
## Warning: package 'readr' was built under R version 4.0.3
## Warning: package 'purrr' was built under R version 4.0.3
## Warning: package 'dplyr' was built under R version 4.0.3
## Warning: package 'stringr' was built under R version 4.0.3
## Warning: package 'forcats' was built under R version 4.0.3
# Import S&P500 Stock Index
SP500 <- tq_index("SP500")
SP500
## # A tibble: 505 x 8
## symbol company identifier sedol weight sector shares_held local_currency
## <chr> <chr> <chr> <chr> <dbl> <chr> <dbl> <chr>
## 1 AAPL Apple Inc. 03783310 20462~ 0.0630 Inform~ 163567360 USD
## 2 MSFT Microsoft~ 59491810 25881~ 0.0556 Inform~ 77379110 USD
## 3 AMZN Amazon.co~ 02313510 20000~ 0.0425 Consum~ 4364972 USD
## 4 FB Facebook ~ 30303M10 B7TL8~ 0.0198 Commun~ 24603848 USD
## 5 GOOGL Alphabet ~ 02079K30 BYVY8~ 0.0192 Commun~ 3076971 USD
## 6 GOOG Alphabet ~ 02079K10 BYY88~ 0.0186 Commun~ 2970943 USD
## 7 TSLA Tesla Inc 88160R10 B616C~ 0.0182 Consum~ 7761108 USD
## 8 BRK.B Berkshire~ 08467070 20733~ 0.0144 Financ~ 19917888 USD
## 9 JPM JPMorgan ~ 46625H10 21903~ 0.0133 Financ~ 31197354 USD
## 10 JNJ Johnson &~ 47816010 24758~ 0.0131 Health~ 26943164 USD
## # ... with 495 more rows
505 rows
8 columns
505 companies
Hint: Use the weight column of the data.
Apple, Miscrosft, Amazon
Hint: Use the sector column of the data.
Health Care, Financials, Industrials, Utilities
Hint: Use the symbol column of the data.
NFLX
Hint: Insert a R code chunk below, type the following code: count(SP500, sector, sort = T)
count(SP500, sector, sort = T)
## # A tibble: 11 x 2
## sector n
## <chr> <int>
## 1 Information Technology 76
## 2 Industrials 73
## 3 Financials 65
## 4 Health Care 63
## 5 Consumer Discretionary 61
## 6 Consumer Staples 32
## 7 Real Estate 30
## 8 Materials 28
## 9 Utilities 28
## 10 Communication Services 26
## 11 Energy 23
Information Technology has the largest number of companies (76).
Hint: Use message, echo and results in the chunk options. Refer to the RMarkdown Reference Guide.