Analyser chaque action de l’indice boursier S&P500. Le but ultime est de trouver les actions qui présentent les meilleures perspectives d’avenir sur une base quantitative. De plus, En prime, nous étudierons les corrélations entre actions pour ajouter de la diversification au portefeuille.
# Lecture de la page web
sp500_html <- read_html("https://en.wikipedia.org/wiki/List_of_S%26P_500_companies")
# Importation des tables provenant de cette page web
tables <- html_table(sp500_html, fill = TRUE)
print(class(tables))
## [1] "list"
C’est le premier tableau (qui est d’ailleurs le seul) de la page web qui nous intéresse. Autrement dit, nous devons récupérer le premier élément de la liste tables :
sp_500_raw <- tables[[1]]
head(sp_500_raw)
## # A tibble: 6 × 8
## Symbol Security GICS Secto…¹ GICS …² Headq…³ Date …⁴ CIK Founded
## <chr> <chr> <chr> <chr> <chr> <chr> <int> <chr>
## 1 MMM 3M Industrials Indust… Saint … 1957-0… 6.67e4 1902
## 2 AOS A. O. Smith Industrials Buildi… Milwau… 2017-0… 9.11e4 1916
## 3 ABT Abbott Health Care Health… North … 1957-0… 1.8 e3 1888
## 4 ABBV AbbVie Health Care Pharma… North … 2012-1… 1.55e6 2013 (…
## 5 ACN Accenture Information… IT Con… Dublin… 2011-0… 1.47e6 1989
## 6 ATVI Activision Blizzard Communicati… Intera… Santa … 2015-0… 7.19e5 2008
## # … with abbreviated variable names ¹`GICS Sector`, ²`GICS Sub-Industry`,
## # ³`Headquarters Location`, ⁴`Date added`
class(sp_500_raw)
## [1] "tbl_df" "tbl" "data.frame"
sp_500 <- sp_500_raw %>%
select(Symbol, Security, `GICS Sector`, `GICS Sub-Industry`) %>%
as_tibble()
print(class(sp_500))
## [1] "tbl_df" "tbl" "data.frame"
head(sp_500)
## # A tibble: 6 × 4
## Symbol Security `GICS Sector` `GICS Sub-Industry`
## <chr> <chr> <chr> <chr>
## 1 MMM 3M Industrials Industrial Conglomerates
## 2 AOS A. O. Smith Industrials Building Products
## 3 ABT Abbott Health Care Health Care Equipment
## 4 ABBV AbbVie Health Care Pharmaceuticals
## 5 ACN Accenture Information Technology IT Consulting & Other Servi…
## 6 ATVI Activision Blizzard Communication Services Interactive Home Entertainm…
On peut faire le même travail pour les entreprises du CAC 40. Lien pour le CAC 40 : https://en.wikipedia.org/wiki/CAC_40
# Nombre de modalités de chaque variable
sp_500 %>%
lapply(function(x) x %>% unique() %>% length()) %>%
unlist()
## Symbol Security GICS Sector GICS Sub-Industry
## 503 503 11 126
Nous avons 505 symboles et 505 entreprises donc tout va bien :)
# Nombre de sociétés par Secteur principal (GICS Sector)
sp_500 %>%
# Grouper par "GICS Sector" et compter le nombre d'observations
group_by(`GICS Sector`) %>%
summarise(count = n()) %>%
# Visualisation
ggplot(aes(x = `GICS Sector` %>% fct_reorder(count),
y = count
)) +
geom_bar(stat = "identity") +
geom_text(aes(label = count), size = 3, nudge_y = 4, nudge_x = .1) +
scale_y_continuous(limits = c(0,100)) +
ggtitle(label = "Nombre de sociétés du S&P500 par Secteur principal") +
xlab(label = "GICS Sector") +
coord_flip()
Une technique d’atténuation des risques consiste à sélectionner des actions ayant une faible corrélation de rendement entre elles. En règle générale, la sélection parmi différents secteurs permet de réduire cette corrélation et de diversifier le portefeuille.
# Création d'une fonction pour récupérer les données d'une entreprise
get_stock_prices <- function(ticker, return_format = "tibble", ...) {
# Get stock prices
stock_prices_xts <- getSymbols(Symbols = ticker, auto.assign = FALSE, ...)
# Rename
names(stock_prices_xts) <- c("Date", "Open", "High", "Low", "Close", "Volume", "Adjusted")
# Return in xts format if tibble is not specified
if (return_format == "tibble") {
stock_prices <- stock_prices_xts %>%
as_tibble() %>%
rownames_to_column(var = "Date") %>%
mutate(Date = ymd(Date))
} else {
stock_prices <- stock_prices_xts
}
stock_prices
}
get_stock_prices <- function(ticker) {
stock_prices <- getSymbols(ticker, auto.assign = F)
names(stock_prices) <- c("Open", "High", "Low", "Close", "Volume", "Adjusted")
stock_prices
}
# Application de la fonction
head(get_stock_prices("MA"))
## Open High Low Close Volume Adjusted
## 2007-01-03 9.955 9.968 9.563 9.641 26289000 8.899554
## 2007-01-04 9.690 10.185 9.530 10.114 27024000 9.336178
## 2007-01-05 10.099 10.220 9.900 10.106 29632000 9.328789
## 2007-01-08 9.901 10.225 9.900 10.108 16006000 9.330636
## 2007-01-09 10.110 10.575 10.060 10.574 36952000 9.760804
## 2007-01-10 10.562 10.650 10.300 10.474 35099000 9.676730
# Fonction pour calculer les logarithmes des rendements journaliers
get_log_returns <- function(x) {
log_returns <- dailyReturn(x = x$Adjusted, type = "log")
log_returns
}
# Application de la fonction get_log_returns
head(get_log_returns(get_stock_prices("MA")))
## daily.returns
## 2007-01-03 0.0000000000
## 2007-01-04 0.0478955940
## 2007-01-05 -0.0007916438
## 2007-01-08 0.0001988271
## 2007-01-09 0.0450705462
## 2007-01-10 -0.0086505375