8 min read

Crypto with Rstudio

Crypto2

Package crypto2 retrieves crypto currency information and historical prices as well as information on the exchanges they are listed on from (CoinMarketCap)https://coinmarketcap.com via their ‘web-api’.

library(crypto2)
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.1 ──
## ✓ ggplot2 3.3.5     ✓ purrr   0.3.4
## ✓ tibble  3.1.6     ✓ dplyr   1.0.7
## ✓ tidyr   1.1.4     ✓ stringr 1.4.0
## ✓ readr   2.1.0     ✓ forcats 0.5.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
coins <- crypto_list(only_active=TRUE)
coin_info <- crypto_info(coins,limit=3)
## > Scraping crypto info
## 
## > Processing historical crypto data
## 
coin_info
## # A tibble: 3 × 19
##      id name     symbol category description     slug   logo    subreddit notice
##   <int> <chr>    <chr>  <chr>    <chr>           <chr>  <chr>   <chr>     <chr> 
## 1     1 Bitcoin  BTC    coin     "## What Is Bi… bitco… https:… bitcoin   ""    
## 2     2 Litecoin LTC    coin     "## What Is Li… litec… https:… litecoin  ""    
## 3     3 Namecoin NMC    coin     "Namecoin (NMC… namec… https:… namecoin  ""    
## # … with 10 more variables: date_added <chr>, twitter_username <chr>,
## #   is_hidden <int>, date_launched <lgl>,
## #   self_reported_circulating_supply <lgl>, self_reported_tags <lgl>,
## #   status <dttm>, tags <list>, urls <list>, platform <lgl>

In addition we show tags provided by https://coinmarketcap.com.

coin_info %>% 
  select(slug,tags) %>% 
  tidyr::unnest(tags) %>% 
  group_by(slug) %>% 
  slice(1,n())
## # A tibble: 6 × 2
## # Groups:   slug [3]
##   slug     tags               
##   <chr>    <chr>              
## 1 bitcoin  mineable           
## 2 bitcoin  paradigm-portfolio 
## 3 litecoin mineable           
## 4 litecoin binance-smart-chain
## 5 namecoin mineable           
## 6 namecoin platform

Additionally: Here are some urls pertaining to these coins as provided by https://coinmarketcap.com.

coin_info %>% 
  select(slug,urls) %>% 
  tidyr::unnest(urls) %>% 
  filter(name %in% c("reddit","twitter"))
## # A tibble: 5 × 3
##   slug     name    url                                
##   <chr>    <chr>   <chr>                              
## 1 bitcoin  reddit  https://reddit.com/r/bitcoin       
## 2 litecoin twitter https://twitter.com/LitecoinProject
## 3 litecoin reddit  https://reddit.com/r/litecoin      
## 4 namecoin twitter https://twitter.com/Namecoin       
## 5 namecoin reddit  https://reddit.com/r/namecoin

In a next step we download time series data for these coins.

# retrieve historical data for all (the first 3) of them
coin_hist <- crypto_history(coins, limit=3, start_date="20210101", end_date="20210105")
## > Scraping historical crypto data
## 
## > Processing historical crypto data
## 
# and give the first two times of information per coin
coin_hist %>% 
  group_by(slug) %>% 
  slice(1:2)
## # A tibble: 6 × 16
## # Groups:   slug [3]
##   timestamp           slug      id name   symbol ref_cur    open    high     low
##   <dttm>              <chr>  <int> <chr>  <chr>  <chr>     <dbl>   <dbl>   <dbl>
## 1 2021-01-02 23:59:59 bitco…     1 Bitco… BTC    USD     2.94e+4 3.32e+4 2.91e+4
## 2 2021-01-03 23:59:59 bitco…     1 Bitco… BTC    USD     3.21e+4 3.46e+4 3.21e+4
## 3 2021-01-02 23:59:59 litec…     2 Litec… LTC    USD     1.26e+2 1.40e+2 1.24e+2
## 4 2021-01-03 23:59:59 litec…     2 Litec… LTC    USD     1.37e+2 1.64e+2 1.36e+2
## 5 2021-01-02 23:59:59 namec…     3 Namec… NMC    USD     4.51e-1 5.10e-1 4.15e-1
## 6 2021-01-03 23:59:59 namec…     3 Namec… NMC    USD     4.26e-1 5.14e-1 4.25e-1
## # … with 7 more variables: close <dbl>, volume <dbl>, market_cap <dbl>,
## #   time_open <dttm>, time_close <dttm>, time_high <dttm>, time_low <dttm>

Alternatively, we could determine the price of these coins in other currencies. A list of such currencies is available as fiat_list()

fiats <- fiat_list()
fiats
## # A tibble: 93 × 4
##       id name                 sign  symbol
##    <int> <chr>                <chr> <chr> 
##  1  2781 United States Dollar $     USD   
##  2  2782 Australian Dollar    $     AUD   
##  3  2783 Brazilian Real       R$    BRL   
##  4  2784 Canadian Dollar      $     CAD   
##  5  2785 Swiss Franc          Fr    CHF   
##  6  2786 Chilean Peso         $     CLP   
##  7  2787 Chinese Yuan         ¥     CNY   
##  8  2788 Czech Koruna         Kč    CZK   
##  9  2789 Danish Krone         kr    DKK   
## 10  2790 Euro                 €     EUR   
## # … with 83 more rows

So we download the time series again depicting prices in terms of Bitcoin and Euro (note that multiple currencies can be given to convert, separated by “,”).

# retrieve historical data for all (the first 3) of them
coin_hist2 <- crypto_history(coins, convert="BTC,EUR", limit=3, start_date="20210101", end_date="20210105")
## > Scraping historical crypto data
## 
## > Processing historical crypto data
## 
# and give the first two times of information per coin
coin_hist2 %>% 
  group_by(slug,ref_cur) %>% 
  slice(1:2)
## # A tibble: 12 × 16
## # Groups:   slug, ref_cur [6]
##    timestamp           slug      id name  symbol ref_cur    open    high     low
##    <dttm>              <chr>  <int> <chr> <chr>  <chr>     <dbl>   <dbl>   <dbl>
##  1 2021-01-02 23:59:43 bitco…     1 Bitc… BTC    BTC     1   e+0 1.00e+0 9.99e-1
##  2 2021-01-03 23:59:41 bitco…     1 Bitc… BTC    BTC     1   e+0 1.00e+0 1.00e+0
##  3 2021-01-02 23:59:06 bitco…     1 Bitc… BTC    EUR     2.42e+4 2.73e+4 2.40e+4
##  4 2021-01-03 23:59:06 bitco…     1 Bitc… BTC    EUR     2.65e+4 2.85e+4 2.64e+4
##  5 2021-01-02 23:59:43 litec…     2 Lite… LTC    BTC     4.30e-3 4.24e-3 4.23e-3
##  6 2021-01-03 23:59:41 litec…     2 Lite… LTC    BTC     4.26e-3 4.93e-3 4.18e-3
##  7 2021-01-02 23:59:06 litec…     2 Lite… LTC    EUR     1.04e+2 1.16e+2 1.02e+2
##  8 2021-01-03 23:59:06 litec…     2 Lite… LTC    EUR     1.13e+2 1.34e+2 1.12e+2
##  9 2021-01-02 23:59:43 namec…     3 Name… NMC    BTC     1.54e-5 1.57e-5 1.31e-5
## 10 2021-01-03 23:59:41 namec…     3 Name… NMC    BTC     1.32e-5 1.52e-5 1.32e-5
## 11 2021-01-02 23:59:06 namec…     3 Name… NMC    EUR     3.71e-1 4.21e-1 3.41e-1
## 12 2021-01-03 23:59:06 namec…     3 Name… NMC    EUR     3.51e-1 4.24e-1 3.50e-1
## # … with 7 more variables: close <dbl>, volume <dbl>, market_cap <dbl>,
## #   time_open <dttm>, time_close <dttm>, time_high <dttm>, time_low <dttm>

Last and least, one can get information on exchanges. For this download a list of active/inactive/untracked exchanges using exchange_list():

exchanges <- exchange_list(only_active=TRUE)
exchanges
## # A tibble: 431 × 6
##       id name         slug         is_active first_historical_… last_historical…
##    <int> <chr>        <chr>            <int> <date>             <date>          
##  1    16 Poloniex     poloniex             1 2018-04-26         2021-11-21      
##  2    22 Bittrex      bittrex              1 2018-04-26         2021-11-21      
##  3    24 Kraken       kraken               1 2018-04-26         2021-11-21      
##  4    32 Bleutrade    bleutrade            1 2018-04-26         2021-10-04      
##  5    34 Bittylicious bittylicious         1 2018-04-26         2021-11-21      
##  6    36 CEX.IO       cex-io               1 2018-04-26         2021-11-21      
##  7    37 Bitfinex     bitfinex             1 2018-04-26         2021-11-21      
##  8    42 HitBTC       hitbtc               1 2018-04-26         2021-11-21      
##  9    50 EXMO         exmo                 1 2018-04-26         2021-11-21      
## 10    61 Okcoin       okcoin               1 2018-04-26         2021-11-21      
## # … with 421 more rows

and then download information on “binance” and “kraken”:

ex_info <- exchange_info(exchanges %>% 
                           filter(slug %in% c('binance','kraken')))
## > Scraping crypto info
## 
## > Processing historical crypto data
## 
ex_info
## # A tibble: 2 × 19
##      id name    slug    description notice   logo  type  date_launched is_hidden
##   <int> <chr>   <chr>   <lgl>       <chr>    <chr> <chr> <chr>             <int>
## 1    24 Kraken  kraken  NA          ""       http… ""    2011-07-28T0…         0
## 2   270 Binance binance NA          "Binanc… http… ""    2017-07-14T0…         0
## # … with 10 more variables: is_redistributable <lgl>, maker_fee <dbl>,
## #   taker_fee <dbl>, spot_volume_usd <dbl>, spot_volume_last_updated <dttm>,
## #   status <dttm>, tags <lgl>, urls <list>, countries <lgl>, fiats <list>

Then we can access information on the fee structure,

ex_info %>% 
  select(contains("fee"))
## # A tibble: 2 × 2
##   maker_fee taker_fee
##       <dbl>     <dbl>
## 1     -0.02     0.075
## 2      0.02     0.04

the amount of cryptocurrencies being traded (in USD)

ex_info %>% 
  select(contains("spot"))
## # A tibble: 2 × 2
##   spot_volume_usd spot_volume_last_updated
##             <dbl> <dttm>                  
## 1      760770042. 2021-11-21 07:40:15     
## 2    31807220533. 2021-11-21 07:40:15

Tidyquant

library(tidyquant)
## Loading required package: lubridate
## 
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
## Loading required package: PerformanceAnalytics
## Loading required package: xts
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## 
## Attaching package: 'xts'
## The following objects are masked from 'package:dplyr':
## 
##     first, last
## 
## Attaching package: 'PerformanceAnalytics'
## The following object is masked from 'package:graphics':
## 
##     legend
## Loading required package: quantmod
## Loading required package: TTR
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
## ══ Need to Learn tidyquant? ════════════════════════════════════════════════════
## Business Science offers a 1-hour course - Learning Lab #9: Performance Analysis & Portfolio Optimization with tidyquant!
## </> Learn more at: https://university.business-science.io/p/learning-labs-pro </>
tiingo_api_key('86771cb62164b5be7a3cbb13db57cf4c8ac4e251')
## Token has been set for this R session only. It is recommended to instead set the `RIINGO_TOKEN` environment variable in an `.Renviron` file using `usethis::edit_r_environ()`, and then restart R.

Candlestick Chart

end = ymd(20211115)
# Tiingo Bitcoin in USD ----
btc_usd <- tq_get(c("btcusd"),
       get    = "tiingo.crypto",
       from   = "2021-09-01",
       to     = "2021-11-19")
 #,resample_frequency = "1day")
btc_usd %>% 
  # change the date format to `Date` for geom_candlestick. 
  mutate(date = as.Date(date)) %>% 
  ggplot(aes(x = date, y = close)) +
    geom_candlestick(aes(open = open, high = high, low = low, close = close),
                      colour_up = "darkgreen", colour_down = "darkred", 
                      fill_up  = "darkgreen", fill_down  = "darkred")  +
    labs(title = "BTCUSD Candlestick Chart", y = "Closing Price", x = "") +
    theme_tq()

eth_usd <- tq_get(c("btcusd"),
       get    = "tiingo.crypto",
       from   = "2021-09-01",
       to     = "2021-11-19")
 #,resample_frequency = "1day")
eth_usd %>% 
  # change the date format to `Date` for geom_candlestick. 
  mutate(date = as.Date(date)) %>% 
  ggplot(aes(x = date, y = close)) +
    geom_candlestick(aes(open = open, high = high, low = low, close = close),
                      colour_up = "darkgreen", colour_down = "darkred", 
                      fill_up  = "darkgreen", fill_down  = "darkred")  +
    labs(title = "ETHUSD Candlestick Chart", y = "Closing Price", x = "") +
    theme_tq()

Pull AAPL stock price

AAPL <- tq_get("AAPL", get = "stock.prices", 
               from = "2021-09-01", to = "2021-11-16")
## Warning: `type_convert()` only converts columns of type 'character'.
## - `df` has no columns of type 'character'
AAPL %>%
    ggplot(aes(x = date, y = close)) +
    geom_candlestick(aes(open = open, high = high, low = low, close = close),
                        colour_up = "darkgreen", colour_down = "darkred", 
                        fill_up  = "darkgreen", fill_down  = "darkred", 
                     size = 1) +
    labs(title = "AAPL Candlestick Chart", 
         subtitle = "Zoomed in, Experimenting with Formatting",
         y = "Closing Price", x = "") + 
    coord_x_date(xlim = c(end - weeks(6), end),
                 ylim = c(130, 160)) + 
    theme_tq()