[R lang 크롤링] 비트코인(암호화폐) 가격 불러오기 in R

암호화폐 정보를 위한 crypto2

최근 암호 화폐의 인기가 높아짐에 따라 암호 화폐 데이터에 대한 정보의 분석도 금융권 데이터 분석에 큰 화두가 되고 있다. 그러다보니 당연히 R에서도 암호 화폐를 전문적으로 다루는 패키지가 개발되었다. crypto2가 바로 그것인데 crypto2는 지금은 제공되고 있지 않는 crypto 패키지의 개선판이다. crypto2에서 제공하는 정보는 암호화폐 정보를 전문적으로 다루는 https://coinmarketcap.com/의 정보를 기반으로 제공하는데 이 사이트에서 제공하는 API를 기반으로 제작되었다. 패키지 자체에서 모든 API 접속이 이루어지기 때문에 사용자는 API 접속 키를 따로 받지 않아도 사용할 수 있는 장점이 있지만 이 사이트에서 제공하는 정보에 한정된다는 단점도 있다.

crypto2 패키지에서는 총 7개의 함수를 제공하는데 이 함수들 중 주요한 함수를 살펴보겠다.

설치

crypto2 패키지는 현재(2020-08-20) CRAN에 정식 등록되어 있기 때문에 install.packages()를 사용하여 간단히 설치가 가능하다.

if (!require(crypto2)) {
  install.packages('crypto2')
  library(crypto2)
}

암호 화페 리스트 가져오기

앞서 설명했듯이 crypto2는 https://coinmarketcap.com/의 정보를 가져온다. 이 정보중에 가장 기본적인 것이 이 사이트에서 제공하는 암호화폐의 리스트를 알아보는 것일 것이다. CMC에서 제공하는 암호화폐의 종류는 crypto_list()를 사용하여 가져올 수 있다. crypto_list()로 가져올수 있는 정보는 id, name, symbol 등 8개의 정보이고 이들은 tibble 형태로 반환된다.

list_crypto <- crypto_list(only_active=TRUE)

glimpse(list_crypto)
## Rows: 9,662
## Columns: 8
## $ id                    <int> 1, 2, 3, 4, 5, 6, 8, 10, 13, 16, 18, 25, 35, 37,~
## $ name                  <chr> "Bitcoin", "Litecoin", "Namecoin", "Terracoin", ~
## $ symbol                <chr> "BTC", "LTC", "NMC", "TRC", "PPC", "NVC", "FTC",~
## $ slug                  <chr> "bitcoin", "litecoin", "namecoin", "terracoin", ~
## $ rank                  <int> 1, 21, 664, 1763, 744, 2394, 1391, 1991, 1708, 7~
## $ is_active             <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ~
## $ first_historical_data <date> 2013-04-28, 2013-04-28, 2013-04-28, 2013-04-28,~
## $ last_historical_data  <date> 2022-08-20, 2022-08-20, 2022-08-20, 2022-08-20,~

위의 결과에서 보이는 바와 같이 현재 CMC에서 제공하는 암호화폐 정보 중 현재 거래되고 있는 암호화폐 총 9,660개의 정보를 가져온다.

이중 ’Bitcoin’과 ’Dogecoin’의 정보는 다음과 같다.

list_crypto |> filter(name %in% c('Bitcoin', 'Dogecoin'))
id name symbol slug rank is_active first_historical_data last_historical_data
1 Bitcoin BTC bitcoin 1 1 2013-04-28 2022-08-20
74 Dogecoin DOGE dogecoin 10 1 2013-12-15 2022-08-20

암호 화페 세부 정보 가져오기

CMC에서 제공하는 암호화폐의 종류를 가져왔으니 이제 분석 대상 암호 화폐의 세부 정보를 가져와야 한다. 특정 암호 화폐의 세부 정보를 가져오기 위해서는 crypto_info()를 사용한다. crypto_info()는 crypto_list()에서 가져온 데이터 중 분석 대상인 데이터에 대한 리스트를 매개변수로 전달하면 해당하는 암호 화폐에 대한 정보를 가져온다.

info_crypto <- crypto_info(list_crypto |> filter(name %in% c('Bitcoin', 'Dogecoin')), finalWait=FALSE)
## > Scraping crypto info
## Scraping  https://web-api.coinmarketcap.com/v1/cryptocurrency/info?id=1,74  with  64  characters!
## > Processing crypto info
## > Sleep for 60s before finishing to not have next function call end up with this data!
glimpse(info_crypto)
## Rows: 2
## Columns: 19
## $ id                               <int> 1, 74
## $ name                             <chr> "Bitcoin", "Dogecoin"
## $ symbol                           <chr> "BTC", "DOGE"
## $ category                         <chr> "coin", "coin"
## $ description                      <chr> "## What Is Bitcoin (BTC)?\n\nBitcoin~
## $ slug                             <chr> "bitcoin", "dogecoin"
## $ logo                             <chr> "https://s2.coinmarketcap.com/static/~
## $ subreddit                        <chr> "bitcoin", "dogecoin"
## $ notice                           <chr> "", ""
## $ date_added                       <chr> "2013-04-28T00:00:00.000Z", "2013-12-~
## $ twitter_username                 <chr> "", "dogecoin"
## $ is_hidden                        <int> 0, 0
## $ date_launched                    <lgl> NA, NA
## $ self_reported_circulating_supply <lgl> NA, NA
## $ self_reported_market_cap         <lgl> NA, NA
## $ tags                             <list> [<tbl_df[28 x 1]>], [<tbl_df[8 x 1]>]
## $ self_reported_tags               <lgl> NA, NA
## $ urls                             <list> [<tbl_df[10 x 2]>], [<tbl_df[12 x 2]>~
## $ platform                         <lgl> NA, NA

crypto_info()의 결과로 가져오는 정보는 총 19개의 열을 가진 tibble 객체이다. 이 객체의 열 중 2개는 중첩된 tibble을 포함한다.

중첩된 tibble은 다음과 같이 unnest()를 사용하면 정보를 확인할 수 있다.

info_crypto |> select(name, tags) |> unnest(tags) |> head()
name tags
Bitcoin mineable
Bitcoin pow
Bitcoin sha-256
Bitcoin store-of-value
Bitcoin state-channel
Bitcoin coinbase-ventures-portfolio
info_crypto |> select(slug, urls) |> unnest(urls) |> head()
slug name url
bitcoin website https://bitcoin.org/
bitcoin message_board https://bitcointalk.org
bitcoin explorer1 https://blockchain.coinmarketcap.com/chain/bitcoin
bitcoin explorer2 https://blockchain.info/
bitcoin explorer3 https://live.blockcypher.com/btc/
bitcoin explorer4 https://blockchair.com/bitcoin

암호 화페 가격 가져오기

암호 화폐를 분석하기 위해서 가장 필요한 것이 암호 화폐의 가격일 것이다. 이 데이터는 당연히 시계열 데이터로 다운로드 될 것이다.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

암호 화폐 가격 데이터를 가져오기 위해서는 crypto_history()를 사용한다. 여기서 가져오는 가격 정보는 주식 정보와 유사한 시가(Open), 고가(High), 저가(Low), 종가(Close)와 이 가격에 사용된 화폐, 거래량 등이다. 주식과 달리 암호 화폐는 장의 시작과 종료가 없기 때문에 CMC에서 측정하는 OHLC는 매일의 시작(0시 0분 0초)과 매일의 끝(23시 59분 59초)을 기준으로 산출된다.

hist_crypto <- crypto_history(list_crypto, limit=3, start_date="20220101", end_date="20220820", finalWait=FALSE)
## > Scraping historical crypto data
## > Processing historical crypto data
timestamp id slug name symbol ref_cur open high low close volume market_cap time_open time_close time_high time_low
2022-01-01 23:59:59 1 bitcoin Bitcoin BTC USD 46311.74 47827.31 46288.49 47686.81 24582667004 902104193385 2022-01-01 2022-01-01 23:59:59 2022-01-01 17:49:00 2022-01-01 00:01:00
2022-01-02 23:59:59 1 bitcoin Bitcoin BTC USD 47680.93 47881.41 46856.94 47345.22 27951569547 895688387523 2022-01-02 2022-01-02 23:59:59 2022-01-02 17:08:00 2022-01-02 18:35:00
2022-01-03 23:59:59 1 bitcoin Bitcoin BTC USD 47343.54 47510.73 45835.96 46458.12 33071628362 878946596803 2022-01-03 2022-01-03 23:59:59 2022-01-03 12:19:00 2022-01-03 20:45:00
2022-01-04 23:59:59 1 bitcoin Bitcoin BTC USD 46458.85 47406.55 45752.46 45897.58 42494677905 868383282082 2022-01-04 2022-01-04 23:59:59 2022-01-04 15:17:00 2022-01-04 19:03:00
2022-01-05 23:59:59 1 bitcoin Bitcoin BTC USD 45899.36 46929.05 42798.22 43569.00 36851084859 824368284530 2022-01-05 2022-01-05 23:59:59 2022-01-05 10:11:00 2022-01-05 22:35:00
2022-01-06 23:59:59 1 bitcoin Bitcoin BTC USD 43565.51 43748.72 42645.54 43160.93 30208048289 816685390313 2022-01-06 2022-01-06 23:59:59 2022-01-06 01:20:00 2022-01-06 09:59:00

crypto_history()로 가져오는 가격 데이터의 간격은 매 1일 간격으로 가져온다. 만약 이 간격을 조절하기 위해서는 ‘interval’ 매개변수를 사용한다. 다음은 주 단위로 가격정보를 가져오는 코드이다.

hist_crypto_weekly <- crypto_history(list_crypto, limit=3, start_date="20220101", end_date="20220820", finalWait=FALSE, interval ="weekly")
## > Scraping historical crypto data
## > Processing historical crypto data
timestamp id slug name symbol ref_cur open high low close volume market_cap time_open time_close time_high time_low
2022-01-03 23:59:59 1 bitcoin Bitcoin BTC USD 47343.54 47510.73 45835.96 46458.12 33071628362 878946596803 2022-01-03 2022-01-03 23:59:59 2022-01-03 12:19:00 2022-01-03 20:45:00
2022-01-10 23:59:59 1 bitcoin Bitcoin BTC USD 41910.23 42199.49 39796.57 41821.26 32104232331 791484886194 2022-01-10 2022-01-10 23:59:59 2022-01-10 05:01:00 2022-01-10 14:37:00
2022-01-17 23:59:59 1 bitcoin Bitcoin BTC USD 43118.12 43179.39 41680.32 42250.55 21690904261 799910089279 2022-01-17 2022-01-17 23:59:59 2022-01-17 00:09:00 2022-01-17 22:18:00
2022-01-24 23:59:59 1 bitcoin Bitcoin BTC USD 36275.73 37247.52 33184.06 36654.33 41856658597 694196560317 2022-01-24 2022-01-24 23:59:59 2022-01-24 20:59:00 2022-01-24 11:07:00
2022-01-31 23:59:59 1 bitcoin Bitcoin BTC USD 37920.28 38647.26 36733.57 38483.13 20734730465 729073641688 2022-01-31 2022-01-31 23:59:59 2022-01-31 19:19:00 2022-01-31 02:07:00
2022-02-07 23:59:59 1 bitcoin Bitcoin BTC USD 42406.78 44401.86 41748.16 43840.29 28641855926 830838884165 2022-02-07 2022-02-07 23:59:59 2022-02-07 19:46:00 2022-02-07 00:50:00

crypto_history()에서의 암호 화폐 가격은 기본적으로 미국 달러(USD)로 설정되어 있다. 만약 이 통화를 다른 통화로 바꾸려면 ‘convert’ 매개변수를 사용한다. ’convert’에서 하나 이상의 통화로 변환하기 위해서는 콤마(,)를 사용하여 통화의 이름을 명기해주면 각각의 통화로 변환된 행들이 추가되어 변환된다.

hist_crypto <- crypto_history(list_crypto, convert = 'EUR, KRW', limit=3, start_date="20220101", end_date="20220820", finalWait=FALSE)
## > Scraping historical crypto data
## > Processing historical crypto data
timestamp id slug name symbol ref_cur open high low close volume market_cap time_open time_close time_high time_low
2022-01-01 23:59:06 1 bitcoin Bitcoin BTC EUR 4.071738e+04 4.204987e+04 4.069693e+04 4.192634e+04 2.161313e+10 7.931318e+11 2022-01-01 2022-01-01 23:59:59 2022-01-01 17:49:00 2022-01-01 00:01:00
2022-08-19 23:59:06 3 namecoin Namecoin NMC EUR 1.105026e+00 1.106187e+00 1.022230e+00 1.029409e+00 5.569530e+03 1.516979e+07 2022-08-19 2022-08-19 23:59:59 2022-08-19 00:48:00 2022-08-19 21:49:00
2022-01-01 23:59:06 1 bitcoin Bitcoin BTC KRW 5.505911e+07 5.686093e+07 5.503146e+07 5.669390e+07 2.922584e+13 1.072494e+15 2022-01-01 2022-01-01 23:59:59 2022-01-01 17:49:00 2022-01-01 00:01:00
2022-08-19 23:59:06 3 namecoin Namecoin NMC KRW 1.479713e+03 1.479443e+03 1.370472e+03 1.380097e+03 7.466896e+06 2.033766e+10 2022-08-19 2022-08-19 23:59:59 2022-08-19 00:48:00 2022-08-19 21:49:00

거래소 리스트와 정보

crypto2에서는 암호 화폐 자체의 정보외에 거래소에 대한 정보를 제공한다. exchange_list()를 사용하면 암호 화폐를 거래하는 거래소 리스트를 가져오고 exchange_info()는 거래소의 수수료나 거래량 등의 상세 정보를 가져올 수 있다.

list_exchanges <- exchange_list(only_active=TRUE)
list_exchanges |> head()
id name slug is_active first_historical_data last_historical_data
16 Poloniex poloniex 1 2018-04-26 2022-08-20
21 BTCC btcc 1 2018-04-26 2022-08-20
22 Bittrex bittrex 1 2018-04-26 2022-08-20
24 Kraken kraken 1 2018-04-26 2022-08-20
34 Bittylicious bittylicious 1 2018-04-26 2022-08-20
36 CEX.IO cex-io 1 2018-04-26 2022-08-20
info_exchange <- exchange_info(list_exchanges |> filter(name %in% c('Upbit', 'Bithumb', 'Korbit', 'Coinone')), finalWait=FALSE)
## > Scraping exchange info
## Scraping exchanges from  https://web-api.coinmarketcap.com/v1/exchange/info?id=174,194,200,351  with  69  characters!
## > Processing exchange info
  id name slug description notice logo type date_launched is_hidden is_redistributable maker_fee taker_fee spot_volume_usd spot_volume_last_updated weekly_visits tags urls countries fiats
174 174 Coinone coinone NA   https://s2.coinmarketcap.com/static/img/exchanges/64x64/174.png   2014-06-11T00:00:00.000Z 0 NA 0 0 130134802 2022-08-20 16:35:16 256177 NA twitter , chat , website , fee , https://twitter.com/CoinoneOfficialhttps://coinone.co.kr/chat/ , https://coinone.co.kr/ , https://coinone.co.kr/fees/ NA KRW
194 194 Korbit korbit NA   https://s2.coinmarketcap.com/static/img/exchanges/64x64/194.png   2013-07-25T00:00:00.000Z 0 NA 0 0 7020274 2022-08-20 16:35:16 36030 NA website , fee , https://www.korbit.co.kr , https://www.korbit.co.kr/notice/?id=6yMDTqvYPYGaGKoBvzKVo2 NA KRW
200 200 Bithumb bithumb Since its launch, Bithumb has developed from a Korea-focused cryptocurrency exchange to one that serves the global market. Bithumb aims to become a comprehensive digital financial corporation based on the blockchain.                              

각각 거래소의 수수료와 거래량은 다음과 같이 알아볼 수 있다.

info_exchange |> select(name, contains("fee"), contains("spot"))
name maker_fee taker_fee spot_volume_usd spot_volume_last_updated
Coinone 0 0 130134802 2022-08-20 16:35:16
Korbit 0 0 7020274 2022-08-20 16:35:16
Bithumb 0 0 600960260 2022-08-20 16:35:16
Upbit 0 0 1509503596 2022-08-20 16:35:16

 

[출처] https://2stndard.tistory.com/125

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
공지 오라클 기본 샘플 데이터베이스 졸리운_곰 2014.01.02 27784
공지 [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE 가을의 곰을... 2013.02.10 27397
공지 [G_SQL] Sample Database 가을의 곰을... 2012.05.20 30579
1077 암호화폐 (비트코인, cryptocurrency, bitcoin) Solidity 이더리움 Cheatsheet 졸리운_곰 2024.01.23 241
1076 [데이터분석 & 데이터 사이언스] 데이터에 관한 꼭 알아야 할 오해와 진실 12가지 졸리운_곰 2024.01.17 280
1075 [tensorflow 1.13 1.x 버전 설치법] [TensorFlow] Anaconda 가상환경 이용하여 TensorFlow GPU 설치 졸리운_곰 2024.01.08 154
» [R lang 크롤링] 비트코인(암호화폐) 가격 불러오기 in R 졸리운_곰 2023.12.11 178
1073 [통계 R 언어] 이동평균이 표시된 plotly 동적 주가 그래프 in R file 졸리운_곰 2023.12.11 275
1072 [R lang 크롤링] 금융 데이터 분석 주가 데이터 가져오기 in R 졸리운_곰 2023.12.11 227
1071 [R lang 크롤링] (R) [전략적가치투자] - 증액 투자법 file 졸리운_곰 2023.12.10 186
1070 [R lang 크롤링] (R) [전략적가치투자] - 정액 투자법 file 졸리운_곰 2023.12.10 178
1069 [R lang 크롤링] (R) [전략적가치투자] - 매입 보유법, 정률 투자법, 변율 투자법 file 졸리운_곰 2023.12.10 208
1068 [R lang 크롤링] (R) wordcloud2로 더 예쁘게 시각화하기 file 졸리운_곰 2023.12.10 228
1067 [R lang 크롤링] (R) 나만의 주식차트만들기 / quantmod 패키지(2) file 졸리운_곰 2023.12.10 247
1066 [R lang 크롤링] (R) R에서 주가정보 가져오기 / quantmod 패키지(1) file 졸리운_곰 2023.12.10 307
1065 [R lang 크롤링] (R) 정규식에서 사용되는 주요 기호들과 의미 file 졸리운_곰 2023.12.10 260
1064 [R lang 크롤링] (R) 종목토론실 텍스트마이닝하여 시각화하기 file 졸리운_곰 2023.12.10 294
1063 [R lang 크롤링] (R) 네이버금융에서 종목토론방 크롤링 file 졸리운_곰 2023.12.10 123
1062 [통계 R 언어] [ R ] pipe operator %>% 의 의미 - magrittr 패키지 졸리운_곰 2023.12.10 170
1061 [R lang 크롤링] [R 코드] 웹사이트 크롤링 졸리운_곰 2023.12.10 215
1060 [R lang 크롤링] R - 크롤링 file 졸리운_곰 2023.12.10 181
1059 [통계 R 언어] [Rtips] 불리는 패키지가 없습니다 해결 방법 file 졸리운_곰 2023.12.10 199
1058 [통계 R 언어] 패키지 설치 에러시 ERROR configuration failed for package RCurl during installation of DESeq file 졸리운_곰 2023.12.10 172
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED