Mostrando entradas con la etiqueta calendarHeat. Mostrar todas las entradas
Mostrando entradas con la etiqueta calendarHeat. Mostrar todas las entradas

2020-03-16

Variaciones diarias de acciones o índices en R


Problema

Queremos crear un mapa de calor en forma de calendario con las variaciones diarias de acciones o índices en R.

Solución

  1. Ejecutamos el código de Paul Bleicher para crear la función calendarHeat. Editamos el código fuente para modificar la paleta de colores si fuera necesario.
  2. Extraemos los datos usando la función getSymbols.
  3. Calculamos las variaciones diarias.
  4. Creamos el gráfico de las series temporales.
Un par de ejemplos:

  1. Dow Jones, emulando la paleta usada por Mike Bostock here. Los días del índice son verde cuando suben y rosas cuando bajan. Los varaciones están calculadas en porcentaje.
  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') # o 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, usando otra paleta de azul a rojo. Los varaciones están calculadas en porcentaje.
  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"
    )
    

Resultados

En los siguentes gráficos, las últimas variaciones diarias desencadenadas por la pandemia del coronavirus (COVID-19) hacen que el resto de días aparezcan muy pálidos en comparación.

Entradas relacionadas

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

Nube de datos