Problem
We want to create a calendar heatmap with the daily changes of stocks or indexes in R.
Solution
- We run the calendarHeat function created by Paul Bleicher to display calendar heatmaps. Editing the palettes in source code if needed.
- We extract the stock or index data using getSymbols.
- We calculate the daily changes.
- We plot the time series.
- Dow Jones, emulating the palette used by Mike Bostock here. Days the index went up are green, and down are pink. The changes are in percentages.
- S&P500, using another palette from blue to red. The changes are in percentages.
library(tidyverse)
library(tidyquant)
# Dow Jones
symb <- getSymbols(Symbols = "^DJI", QQQ = 'yahoo', auto.assign = FALSE)
n <- gsub("^.*\\.", "", names(symb))
symb <- as.data.frame(symb)
colnames(symb) <- n
symb$date <- rownames(symb)
rownames(symb) <- NULL
df <- symb %>%
mutate(date = as.Date(date),
pct_vol = round(100 * (Adjusted / lag(Adjusted) - 1), 2)) %>%
filter(!is.na(pct_vol), date >= '2016-01-01', date <= '2020-12-31') # or filter(!is.na(pct_vol), date >= '2011-01-01', date <= '2015-12-31')
calendarHeat(
df$date,
df$pct_vol,
varname = "Dow Jones Industrial Average",
ncolors = 50,
color = "g2p"
)
symb <- getSymbols(Symbols = "^GSPC", QQQ = 'yahoo', auto.assign = FALSE)
n <- gsub("^.*\\.", "", names(symb))
symb <- as.data.frame(symb)
colnames(symb) <- n
symb$date <- rownames(symb)
rownames(symb) <- NULL
df <- symb %>%
mutate(date = as.Date(date),
pct_vol = round(100 * (Adjusted / lag(Adjusted) - 1), 2)) %>%
filter(!is.na(pct_vol), date >= '2016-01-01', date <= '2020-12-31')
calendarHeat(
df$date,
df$pct_vol,
varname = "S&P 500",
ncolors = 50,
color = "b2r"
)
Results
In the next two plots, because of the large daily variations in the last days due to the coronavirus pandemic (COVID-19), the rest of the days are very pale in comparison.Related posts
No hay comentarios:
Publicar un comentario