Code for picking the best cryptos from coinmarketcap


#1

Code for 2017 crypto awards. Using R programming language.

library(magrittr)
library(ggplot2)
library(rvest)
library(httr)

make_numeric <- function(x) {
  x %>% gsub(' ', '', .) %>% gsub('\\$', '', .) %>%
  gsub(',', '', .) %>% gsub('\\*', '', .) %>% as.numeric
}

# get all cryptos listed on coinmarketcap
all_ids <- GET("https://api.coinmarketcap.com/v1/ticker/?limit=0") %>%
  content %>% sapply(`[[`, "id")

# pull price data for every crypto on coinmarketcap
all_data <- pbapply::pblapply(all_ids, function(id) {
  url = paste0('https://coinmarketcap.com/currencies/', id, '/historical-data/?start=20170101&end=20180101')
  page <- read_html(url)
  coindata <- page %>%
    html_node("table") %>% html_table(fill = TRUE) %>%
    `names<-`(., c("date", "open", "high", "low", "close", "volume", "market_cap"))

  coindata$volume     %<>% make_numeric
  coindata$market_cap %<>% make_numeric
  coindata$date %<>% as.Date(., format="%b %d, %Y")

  plyr::arrange(coindata, date)
})
names(all_data) <- all_ids

# You can then calculate gains like this
gains <- lapply(all_data, function(df) {
  prices <- df$open
  if (!is.numeric(prices)) { return(NA) }
  if (!is.numeric(df$market_cap[1])) { return(NA) }
  if (isTRUE(df$market_cap[1] < 1000000)) { return(NA) }
  tail(prices, 1) / head(prices, 1)
})