Daily Coding - Calendar Heatmap of Stock Returns using R

In this post, we will see one of the way of plotting a calendar heatmap of stock returns using only a Red / Green palette in R.
We will use data from a previous post on analyzing FAANG stocks.
require(openair)
require(data.table)
tickers <- c("FB", "AMZN", "AAPL", "NFLX", "GOOG", "SPY")
getYahooData <- function(ticker ,n=-1){
require('quantmod')
print(paste('Getting yahoo data for ...',ticker))
## Obtain symbol data
getSymbols(ticker, from="2010-01-01")
stock <- get(ticker)
## Utilise the backwards-adjusted closing prices
stock.uA <- adjustOHLC(stock, use.Adjusted=TRUE)
stock <- Cl(stock.uA)
assign(ticker, stock, envir=.GlobalEnv)
}
none <- sapply(tickers, getYahooData)
# https://stackoverflow.com/questions/44911304/merging-multiple-xts-objects-by-index
# credit: [How to pass extra argument to the function argument of do.call in R - Stack Overflow](https://stackoverflow.com/questions/10119893/how-to-pass-extra-argument-to-the-function-argument-of-do-call-in-r)
all.xts <- do.call('merge', sapply(tickers, get))
all.xts <- all.xts["2015::"]
require("gdata")
clean_names <- sapply(names(all.xts), function(name) {gsub(".Close", "", name)})
names(all.xts) <- clean_names
# lets get the time from which we have all data
# [r - Remove rows with all or some NAs (missing values) in data.frame - Stack Overflow](https://stackoverflow.com/questions/4862178/remove-rows-with-all-or-some-nas-missing-values-in-data-frame)
all.xts <- all.xts[complete.cases(all.xts), ]
require(PerformanceAnalytics)
all.xts.ret <- Return.calculate(all.xts)
spy.xts.ret <- subset(all.xts.ret, select = c(SPY))
require(lubridate)
dt <- as.data.table(spy.xts.ret)
setnames(dt, c("index", "SPY"), c("date", "return"))
dt[,return:=100*return]
dt
calendarPlot(dt, pollutant="return", year=2019,
cols=c("darkred", "red", "gray", "green", "darkgreen"),
main="S&P500 returns in % (2019)")
