2020-03-16

Daily changes of stocks in R


Problem

We want to create a calendar heatmap with the daily changes of stocks or indexes in R.

Solution

  1. We run the calendarHeat function created by Paul Bleicher to display calendar heatmaps. Editing the palettes in source code if needed.
  2. We extract the stock or index data using getSymbols.
  3. We calculate the daily changes.
  4. We plot the time series.
Let's see a couple of examples:

  1. 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.
  2. 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"
    )
    
  3. S&P500, using another palette from blue to red. The changes are in percentages.
  4. 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

Nube de datos