본문 바로가기

프로젝트/가격예측프로젝트

(spring boot + flask + deep learning) 이더리움 가격 예측 웹 앱 서비스(2) - 업비트 API 로 일봉 데이터 받아오기

업비트 API를 이용해서 일봉 데이터를 받아오고자 한다.

먼저 데이터를 받아와서 데이터베이스에 저장을 하려면 엑셀 파일로 받는 것이 가장 쉽다. 그래서 API로 데이터를 받아와서 엑셀에 저장 하는 것을 구현해보았다.

from numpy import log
import requests
import pandas as pd
import time
import json
from pandas import json_normalize
import time
from datetime import datetime, timedelta
from time import sleep

"""
request params
market : 마켓 코드(KRW-BTC)
to : 마지막 캔들 시간 포맷 : yyyy-MM-dd'T'HH:mm:ss'Z' or yyyy-MM-dd HH:mm:ss. 비워서 요청시 가장 최근 캔들
count : 캔들 갯수

response 
String	market : 종류
String	candle_date_time_utc : 시간
String	candle_date_time_kst
Integer	opening_price : 시초가
Integer	high_price : 고가
Integer	low_price : 저가
Integer	trade_price : 체결가
Integer	timestamp : 
prev_closing_price : 이전 종가
Number	candle_acc_trade_price : 누적 거래량
Number	candle_acc_trade_volume : 누적 체결가
String	first_day_of_period

"""

coin_list = ['BTC', ETH', 'DOGE', 'XRP', 'ETC', 'ADA']

base_dir = "/Users/file"

for coin in coin_list:
	default_time = 0
    input_excel_data = []
    
	# 우선 500일 전까지 받아오기로 한다. 
    
    while default_time < 500:
        default_time += 1
        time1 = (datetime.now() - timedelta(days=default_time)).strftime('%Y-%m-%dT%H:%M:%SZ')
        
        
        # 계속 while문을 돌리면 10개 정도에서 400대 에러가 나는 것이 확인되었다. 보니 api를 적은 시간내에
        # 많이 요청해서 생긴 문제이기 때문에 10이 배수에서 잠깐 쉬어주는 코드를 넣어주었다.
        
        if default_time % 10 == 0:
            sleep(10)
        
        url = f"https://api.upbit.com/v1/candles/days"
        querystring = {"market":f"KRW-{coin}",
                        "count":"1",
                        "convertingPriceUnit":"KRW",
                        "to":time1}
        headers = {"Accept": "application/json",
                    'Content-Type': 'application/json'}
        response_json = requests.request("GET", url, headers=headers, params=querystring)
        print(response_json)
        response_json = response_json.json()
        
        
        if response_json == []:
            break
        
        input_excel_data.append({
                'market'                  : response_json[0]["market"],
                'candle_date_time_kst'    : response_json[0]["candle_date_time_kst"],
                'opening_price'           : response_json[0]["opening_price"],
                'high_price'              : response_json[0]["high_price"],
                'low_price'               : response_json[0]["low_price"],
                'trade_price'             : response_json[0]["trade_price"],
                'timestamp'               : response_json[0]["timestamp"],
                'candle_acc_trade_price'  : response_json[0]["candle_acc_trade_price"],
                'candle_acc_trade_volume' : response_json[0]["candle_acc_trade_volume"],
                'prev_closing_price'      : response_json[0]["prev_closing_price"],
                'change_price'            : response_json[0]["change_price"],
                'change_rate'             : response_json[0]["change_rate"],
                'converted_trade_price'   : response_json[0]["converted_trade_price"]

            })

        
            
            
    print('input_excel_data', input_excel_data)
        

    excel_data = pd.DataFrame(input_excel_data)
    excel_data.to_excel(f"{base_dir}/{coin}days.xlsx")
                

우선 모든 코인을 가져오기 보다는 관심있는 코인들 몇 가지를 리스트에 넣어주었다.

그리고 어떻게 데이터를 엑셀에 넣을까 고민하다가 한번 가져오는 데이터가 [{}] 로 가져오길래 input_excel_data 안에다가 dictionary 형태로 정보를 넣고 dataframe 형태로 만든 다음에 엑셀 파일로 변경하는 작업을 했다.

 

코드는 쉽게 짰지만 중간에 계속 멈춰서 왜 그런지 고민을 했는데 10단위별로 계속 400에러는 뱉는 것을 확인 하고 중간에 쉬어주는 타이밍을 넣었다.

 

위에 코드는 업비트 API Doc 을 보면서 구현하면 훨씬 더 잘 이해 될 것이다.