Mostrando entradas con la etiqueta tidyverse. Mostrar todas las entradas
Mostrando entradas con la etiqueta tidyverse. 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

2019-11-01

Cómo reordenar diagramas de barras en ggplot2

Problema

Queremos reodernar las barras de un diagrama de barras creado con ggplot2. En nuestro ejemplo, se puede observar que las barras no están ni en orden ascendente o descendente.

library(tidyverse)
ggplot(df, aes(x = Position)) + geom_bar()
  • Data frame
  • df <- structure(list(Position = structure(c(3L, 3L, 1L, 1L, 1L, 2L), .Label = c("Defense", 
    "Striker", "Zoalkeeper"), class = "factor"), Name = structure(c(2L, 
    1L, 3L, 5L, 4L, 6L), .Label = c("Frank", "James", "Jean", "John", 
    "Steve", "Tim"), class = "factor")), class = "data.frame", row.names = c(NA, 
    -6L))
    
        Position  Name
    1 Zoalkeeper James
    2 Zoalkeeper Frank
    3    Defense  Jean
    4    Defense Steve
    5    Defense  John
    6    Striker   Tim
    

    Solución

    Una alternativa es usar reorder para reordenar los niveles del factor. En orden ascendente (n) o descendente (-n) en función del conteo de la columna Position.

    • Orden ascendente
    • df %>%
        count(Position) %>%
        ggplot(aes(x = reorder(Position, n), y = n)) +
        geom_bar(stat = 'identity') +
        xlab("Position")
      
    • Orden descendente
    • df %>%
        count(Position) %>%
        ggplot(aes(x = reorder(Position, -n), y = n)) +
        geom_bar(stat = 'identity') +
        xlab("Position")
      

    Entradas relacionadas

    Referencias

    2019-10-23

    How to reorder bar charts with ggplot2

    Problem

    We'd like to reorder the bars of a bar chart. In our example below, the bars are not plotted in ascending or descending order.

    library(tidyverse)
    ggplot(df, aes(x = Position)) + geom_bar()
    
  • Data frame
  • df <- structure(list(Position = structure(c(3L, 3L, 1L, 1L, 1L, 2L), .Label = c("Defense", 
    "Striker", "Zoalkeeper"), class = "factor"), Name = structure(c(2L, 
    1L, 3L, 5L, 4L, 6L), .Label = c("Frank", "James", "Jean", "John", 
    "Steve", "Tim"), class = "factor")), class = "data.frame", row.names = c(NA, 
    -6L))
    
        Position  Name
    1 Zoalkeeper James
    2 Zoalkeeper Frank
    3    Defense  Jean
    4    Defense Steve
    5    Defense  John
    6    Striker   Tim
    

    Solution

    An alternative is using reorder to order the levels of a factor. In ascending (n) or descending order (-n) based on the count:

    • Descending order
    • df %>%
        count(Position) %>%
        ggplot(aes(x = reorder(Position, -n), y = n)) +
        geom_bar(stat = 'identity') +
        xlab("Position")
      
    • Ascending order
    • df %>%
        count(Position) %>%
        ggplot(aes(x = reorder(Position, n), y = n)) +
        geom_bar(stat = 'identity') +
        xlab("Position")
      

    References

    2019-04-08

    Quantile-quantile (Q-Q) plots with ggplot2

    Problem

    We'd like to create quantile-quantile (Q-Q) plots using ggplot2.

    Solution

    • Option 1: one column.
    • We create two examples using one column of a data frame. In the first example, we previously transform the vector rivers into a data frame. In the second, we use the column Volume from the data frame trees.

      library(tidyverse)
      ggplot(data.frame(rivers), aes(sample = rivers)) + stat_qq() + stat_qq_line()
      ggplot(trees, aes(sample = Volume)) + stat_qq() + stat_qq_line()
      
    • Option 2: multiple columns.
    • We compare the distribution of Miles/(US) gallon by number of cylinders (cyl).

      ggplot(mtcars, aes(sample = mpg, colour = factor(cyl))) +
        stat_qq() +
        stat_qq_line()
      
    • Option 3: multiple panels.
    • In this first example no transformation is needed because a column of the data frame contains the groups..

      ggplot(mtcars, aes(sample = mpg)) +
        facet_wrap( ~ factor(cyl)) +
        stat_qq() +
        stat_qq_line()
      
      In the second example, we convert the data frame from wide format to long format for faceting into multiple panels with facet_wrap. Instead of 31 observations for 3 variables, we will have one column condition containing 93 observaciones for the 3 variables.

      gather(trees, condition, measurement, Girth:Volume, factor_key = TRUE) %>%
        ggplot(aes(sample = measurement)) +
        facet_wrap( ~ condition, scales = "free") +
        stat_qq() +
        stat_qq_line()
      
      In the third example, we convert from wide to long, facet by chemical composition, and use a colour for each kiln.

      library(HSAUR2)
      gather(pottery, condition, measurement, Al2O3:BaO, factor_key = TRUE) %>%
        ggplot(aes(sample = measurement, colour = kiln)) +
        facet_wrap(~ condition, scales = "free") +
        stat_qq() +
        stat_qq_line()
      

    References

    2019-03-09

    Gráficos Q-Q con ggplot2

    Problema

    En entradas anteriores explicamos como crear un gráfico Q-Q con el paquete stats preinstalado por defecto. En esa ocasión mostraremos cómo crear estos gráficos con ggplot2.

    Solución

    • Opción 1: única columna.
    • Creamos dos ejemplos de una sola columna de un data frame. En el primero el vector rivers que transformamos previamente en un data frame, y en el segundo la columna Volume del data frame trees.

      library(tidyverse)
      ggplot(data.frame(rivers), aes(sample = rivers)) + stat_qq() + stat_qq_line()
      ggplot(trees, aes(sample = Volume)) + stat_qq() + stat_qq_line()
      
    • Opción 2: múltiples columnas.
    • Comparamos las distribuciones de Miles/(US) gallon por número de cilindros (cyl).

      ggplot(mtcars, aes(sample = mpg, colour = factor(cyl))) +
        stat_qq() +
        stat_qq_line()
      
    • Opción 3: múltiples paneles.
    • En este primer ejemplo no es necesario realizar ninguna transformación porque el data frame tiene una columna con los grupos.

      ggplot(mtcars, aes(sample = mpg)) +
        facet_wrap( ~ factor(cyl)) +
        stat_qq() +
        stat_qq_line()
      
      En este segundo ejemplo transformamos el data frame de formato ancho a largo para poder crear los paneles con facet_wrap. En lugar de tener 31 observaciones para 3 variables, tendremos una columna condition con las 3 variables y 93 observaciones.

      gather(trees, condition, measurement, Girth:Volume, factor_key = TRUE) %>%
        ggplot(aes(sample = measurement)) +
        facet_wrap( ~ condition, scales = "free") +
        stat_qq() +
        stat_qq_line()
      
      En este tercer ejemplo empleamos múltiples colores en función del kiln en cada panel por sustancia química encontrada.

      library(HSAUR2)
      gather(pottery, condition, measurement, Al2O3:BaO, factor_key = TRUE) %>%
        ggplot(aes(sample = measurement, colour = kiln)) +
        facet_wrap(~ condition, scales = "free") +
        stat_qq() +
        stat_qq_line()
      

    Entradas relacionadas

    Referencias

    Nube de datos