You've successfully subscribed to MyPad Blog
Great! Next, complete checkout for full access to MyPad Blog
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

Daily Coding - Calendar Heatmap of Stock Returns using R

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.


tickers <- c("FB", "AMZN", "AAPL", "NFLX", "GOOG", "SPY")

getYahooData <- function(ticker ,n=-1){
  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)

# credit: [How to pass extra argument to the function argument of in R - Stack Overflow](

all.xts <-'merge', sapply(tickers, get))

all.xts <- all.xts["2015::"]

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](
all.xts <- all.xts[complete.cases(all.xts), ]

all.xts.ret <- Return.calculate(all.xts)

spy.xts.ret <- subset(all.xts.ret, select = c(SPY))


dt <-

setnames(dt, c("index", "SPY"), c("date", "return"))


calendarPlot(dt, pollutant="return", year=2019,
             cols=c("darkred", "red", "gray", "green", "darkgreen"),
             main="S&P500 returns in % (2019)")