코인 거래 데이터를 읽어와 그래프를 그려보자 -2

in kr •  7 years ago 

이번에는 저번 포스팅에 이어 하나의 화면에 여러 그래프를 겹쳐 그리는 작업을 진행할 예정입니다.

예상대로만 된다면, 하나의 화면에서 모든 코인의 거래정보를 볼수가 있게 되겠죠^^

모든 코인 정보 불러오기

기본적인 사용법은 이전 포스팅에서 이야기한 내용과 거의 동일 합니다.
다만, 모든 코인을 받아 온다는 점이 다르겠죠

그럼 처음은 모든 코인 데이터를 전부 받아 오고 나서,

import urllib
import json
import time
import matplotlib.pylab as plt

def get_coin_info(coin_type):
    url = "https://api.coinone.co.kr/trades/?currency={0}&period=hour".format(coin_type)
    response = urllib.urlopen(url)
    data = json.loads(response.read())

    price_list = []
    for complete_order in data["completeOrders"]:
        price_list.append(int(complete_order["price"]))
      
    return price_list

coin_type_info = {'btc':None, 'bch':None, 'eth':None, 'etc':None, 'xrp':None, 'qtum':None, 'ltc':None, 'iota':None, 'btg':None}

for coin_type in coin_type_info.keys():
    price_list = get_coin_info(coin_type)
    coin_type_info[coin_type] = price_list

다음과 같이 그래프를 그려주면 되겠죠

fig = plt.figure(figsize=(16,4))
ax = fig.add_subplot(1, 1, 1)

for coin_type, price_list in coin_type_info.items():
    ax.plot(price_list)

plt.show()

output_5_0.png

일단 모든 데이터를 하나의 화면에 그린다라는 목표는 달성 했지만, 이게 무슨 그래프인지 알수가 없는 상황이 발생해 버렸죠.

곰곰이 생각해 보면 몇가지 문제가 있었다는걸 깨다를수 있습니다.

  • 어떤 그래프가 어떤 코인인지 알 수 없다.
  • 코인마다 가격이 다르다
  • 1시간동안 거래된 거래 횟수가 코인마다 다르다

위의 문제를 하나씩 해결해 보도록 하겠습니다.

어떤 그래프가 어떤 코인인지 알 수 없다.

이 문제는 쉽게 생각하면 옆에 범주하나만 추가해 주면 됩니다.
사용중인 matplotlib 라이브러리에서 범례를 추가하려면...
일단 구글링을 통해 다음과 같이 범례를 추가할 수 있다는걸 알게 되었습니다.

ax.plot(data, label='범례')
ax.legend()

그럼 위의 코드를 살짝 수정해 보면 다음과 같은 결과를 얻을수가 있겠죠

fig = plt.figure(figsize=(16,4))
ax = fig.add_subplot(1, 1, 1)

for coin_type, price_list in coin_type_info.items():
    ax.plot(price_list, label=coin_type)
    
ax.legend()
plt.show()

output_8_0.png

코인마다 가격이 다르다.

코인마다 가격이 다르기 때문에 특정한 기준으로 통일을 시켜야 한다는건 알수가 있습니다. 이 경우 표준화를 진행하면 좀더 보기 좋은 데이터를 확인할 수 있습니다.

여기에서 잠깐 - 표준화, 정규화

데이터를 비교할때 표준화(Standardization), 정규화(Normalization) 작업을 많이 거치게 됩니다.

  • 표준화(Standardization)란
    • 평균을 기준으로 얼마나 떨어져 있는지를 표시
    • 2개 이상의 대상이 단위가 다를때 사용 (ex, btc, rep의 비교)
    • 수식: (요소값-평균) / 표준편차
  • 정규화(Normalization)란
    • 데이터를 0 ~ 100사이의 데이터로 변경하여 표시
    • 특정 데이터가 가지는 위치를 보고 싶을 경우 (ex, 과거의 btc정보와 현재의 btc의 비교)
    • 수식: (요소값-최소값) / (최대값-최소값)
import numpy as np

def standardization(price_list):
    data = np.array(price_list)
   
    standard_data = []
    for d in price_list:
        n_data = (d-np.mean(data)) / np.std(data)
        standard_data.append(n_data)
    
    return standard_data

fig = plt.figure(figsize=(16,4))
ax = fig.add_subplot(1, 1, 1)

for coin_type, price_list in coin_type_info.items():
    standard_data = standardization(price_list)
    ax.plot(standard_data, label=coin_type)
    
ax.legend()
plt.show()

output_12_0.png

1시간동안 거래된 거래 횟수가 코인마다 다르다

사용하고 있는 데이터가 최근 한시간 동안의 채결 건수를 보여주다보니, 코인마다 거래량이 다르다는 문제가 있습니다.
이를 해결하기 위해서 거래들을 시간단위로 나누어 계산을 해보았습니다.

이전까지의 데이터는 시간에 상관없이 그래프를 그렸었지만, 시간을 사용하기 위해서 데이터를 다시 읽어와 재 가공을 했습니다.

import urllib
import json
import time
import matplotlib.pylab as plt

time_list = []
def get_coin_info(coin_type):
    url = "https://api.coinone.co.kr/trades/?currency={0}&period=hour".format(coin_type)
    response = urllib.urlopen(url)
    data = json.loads(response.read())

    price_info = {}
    for complete_order in data["completeOrders"]:
        timestamp = int(complete_order["timestamp"])
        price = int(complete_order["price"])
        price_info[timestamp] = price
        
        if timestamp not in time_list:
            time_list.append(timestamp)
      
    return price_info

coin_type_info = {'btc':None, 'bch':None, 'eth':None, 'etc':None, 'xrp':None, 'qtum':None, 'ltc':None, 'iota':None, 'btg':None}

for coin_type in coin_type_info.keys():
    price_info = get_coin_info(coin_type)
    coin_type_info[coin_type] = price_info

time_list.sort()
import numpy as np

def standardization(price_info):
    data = np.array(price_info.values())
   
    standard_data = {}
    for (timestamp, price) in price_info.items():
        
        n_data = (price-np.mean(data)) / np.std(data)
        standard_data[timestamp] = n_data
    
    return standard_data


def get_chart_data(standard_data):
    chart_data = []
    for timestamp in time_list:
        if timestamp in standard_data:
            price = standard_data[timestamp]
        else:
            if len(chart_data) == 0:
                price = None
            else:
                price = chart_data[-1]
                
                
        chart_data.append(price)
        
    return chart_data
    

fig = plt.figure(figsize=(16,10))
ax = fig.add_subplot(1, 1, 1)

for coin_type, price_info in coin_type_info.items():
    if coin_type not in ['btc', 'iota', 'xrp']:
        continue
    standard_data = standardization(price_info)
    chart_data = get_chart_data(standard_data)
    ax.plot(chart_data, label=coin_type)
    
ax.legend()
plt.show()

output_16_0.png

위의 그래프는 최근 btc, iota, xrp 의 데이터만 출력을 해본 결과입니다.
해당 작업을 통해서 이미 그래프를 그리기 전에 아는 내용이겠지만, 모든 코인은 비슷한 동향으로 움직인다라는것을 다시한번 확인할 수 있었습니다.

해당 포스팅에서는 순수하게 파이썬 코딩을 이용해 데이터를 수집/가공/처리하여 그래프를 그려보는 작업을 진행했습니다.
데이터 처리를 해보신 분들은 아시겠지만, pandas등의 라이브러리를 이용하면 좀더 쉽게 데이터 가공을 할수도 있습니다.

해당 포스팅에서 진행한 내용은 아주 사소한 내용이고, 대부분 알수 있는 내용이겠지만, 데이터 수집, 가공, 처리 하는 내용은 별반 다르지 않습니다. 좀더 세부적이고, 체계적이고, 전략적이고, 계획적이다는 점만 빼고요.(먼가... 음...)

해당 포스팅은 이정도로 마치고, 다음 포스팅에는 그래프를 그리기 위해 수집했던 많은 내용들을 정리해 공유해 보도록 하겠습니다.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!