암호화폐 Cryptocurrency

암호화폐 라인 그래프 작성을 위한 fastquant 및 plotly 라이브러리 사용

coding art 2021. 8. 29. 18:00
728x90

구글 Colaboratory 첫 번째 셀에서 !pip install fastquant를 실행하자. fastquant 는 암호화폐 시장 정보를 유료 서비스하는 업체명이다.

특정한 암호화폐 데이터를 불러 오기 위한 기본 라이브러리는 get_crypto_data 이며 주식은 별도록 stock 으로 명명된다. 그래프 작성을 지원할 수 있도록 plotly를 불러온다. 컬럼 데이터 처리를 위해 pandas를 부르자. 마지막으로 시간 데이터 처리를 위해 파이선 datetime을 불러 설정한다.

변수 now 는 연월일로 설정하자. fastquant 사이트로부터 암호화폐 데이터를 불러오자. 화폐단위 예를 들면 비트코인은 BTC, 이더리움은 ETH 가 된다. /USDT 는 스테이블 코인 가격을 뜻한다. US 달러 가격을 뜻하는 것으로 파악하면 된다. KRWBTC 는 사용할 수 없다. 데이터 시작 날짜와 now를 입력하면 일해당하는 일데이터가 호출된다.

DataFrame을 편집하여 새로 구성하게 되면 index들이 있던 그대로 옮겨오므로 index가 순차적이지 못하게 된다. 따라서 reset_index() 명령 실행에 의해 01234... 와 같이 순차적으로 재편성 해주게 된다.

그래프 작성을 위한 구성 요소 BTC를 준비하자. 이 예제에서는 날짜, 시가 및 종가로 구성이 된다. BTC 가 구성되었다면 DataFrame 명령에 의해 pandas df가 준비된다.

print(‘btc: \n ’, BTC.head()) 출력 결과는 다음과 같다.

준비된 df를 사용하여 plotlyFigure 명령에 의한 그래프를 작성하자. add_trace 명령 별로 각각의 그래프를 작성하도록 하자. 첫 번째로 x좌표는 dfDate 컬럼에서 가져오고 y좌표는 btc_open에서 가져온다. 그래프 모드를 line으로, 라인 색상은 Black으로 설정하자. 두 번째로 add_trace를 사용하여 btc_close 의 컬럼 데이터를 사용하며 색상을 부여한다.

다음은 2021829일의 비트코인 USDT 가격 그래프이며 오능의 종가는 약 47k 즉 약 47000 달러이다.

 

#crypto_line이와 같이 시가와 종가 동시 작도가 가능하다면 고가 저작 데이터를 함께 작도할 수 있을 것이다. 이와 같이 날짜별로 시가 저가 고가 종가를 포함하는 순차적인 학습 데이터 준비가 가능하다면 LSTM 머신러닝이 가능해지게 된다.

 

#crypto_line.ipynb

!pip install fastquant

 

#import the libraries

from fastquant import get_crypto_data

import plotly.graph_objects as go

import pandas as pd

from datetime import datetime

 

#set a date variable

now = datetime.today().strftime('%Y-%m-%d')

print('current date: ', now)

#pull in the data

BTC = get_crypto_data("BTC/USDT""2021-02-01", now) 

#reset the indexes of each df

BTC = BTC.reset_index()

print('btc: ', BTC.head())

 

#keep only the date and the close column

#rename the cloumns

BTC = BTC[['dt','open','close']].rename(columns={"dt""Date""open""btc_open","close""btc_close"})

print('btc: \n ', BTC.head())

#merge all the dataframes

df = pd.DataFrame(BTC)

#print(df.info)

 

#plot it!

fig = go.Figure()

#create lines/traces

fig.add_trace(go.Scatter(x=df['Date'], y=df['btc_open'],

                    mode='lines',

                    name='BTC',

                    line=dict(color="Black", width=2)))

fig.add_trace(go.Scatter(x=df['Date'], y=df['btc_close'],

                    mode='lines',

                    name='BTC',

                    line=dict(color="Red", width=2)))

#update axis ticks

fig.update_yaxes(nticks=30,showgrid=True)

fig.update_xaxes(nticks=12,showgrid=True)

#update layout

fig.update_layout(title="<b>Daily RSI</b>"

                 , height = 700

                 , xaxis_title='Date'

                 , yaxis_title='Relative Strength Index'

                 , template = "plotly" #['ggplot2', 'seaborn', 'simple_white', 'plotly', 'plotly_white', 'plotly_dark']

                 )

#update legend

fig.update_layout(legend=dict(

    orientation="h",

    yanchor="bottom",

    y=1.02,

    xanchor="right",

    x=1

))

#show the figure

fig.show()