본문 바로가기
Python, API

[Python] 체결데이터로 분봉(OHLCV) 만들기

by 오늘밤날다 2023. 6. 4.

 

 

1. 가상의 체결데이터 준비

 

Random 함수를 사용해서 임의의 시간대와 가격, 거래량 자료를 생성하기

# 틱데이터 저장용 변수
tick_data = {'000000': {}}

# 가상의 틱데이터 생성
start_ts = 1685750400  # 2023-06-03 09:00:00
end_ts = 1685774700  # 2023-06-03 15:45:00
for i in range(10):  # 테스트 10개 생성
    timestamp = random.randrange(start_ts, end_ts)
    datetime_item = datetime.fromtimestamp(timestamp)
    price_item = random.randrange(10000, 11000)
    volume_item = random.randrange(1, 51)
    tick_data['000000'][datetime_item] = {'price': price_item, 'volume': volume_item}

 

[실행결과]

{'000000': {datetime.datetime(2023, 6, 3, 9, 51, 50): {'price': 10237,
                                                       'volume': 14},
            datetime.datetime(2023, 6, 3, 10, 52, 54): {'price': 10321,
                                                        'volume': 27},
            datetime.datetime(2023, 6, 3, 11, 28, 11): {'price': 10443,
                                                        'volume': 4},
            datetime.datetime(2023, 6, 3, 11, 37, 53): {'price': 10764,
                                                        'volume': 45},
            datetime.datetime(2023, 6, 3, 11, 40, 36): {'price': 10159,
                                                        'volume': 32},
            datetime.datetime(2023, 6, 3, 12, 24, 6): {'price': 10263,
                                                       'volume': 47},
            datetime.datetime(2023, 6, 3, 13, 31, 6): {'price': 10944,
                                                       'volume': 23},
            datetime.datetime(2023, 6, 3, 14, 1, 37): {'price': 10449,
                                                       'volume': 11},
            datetime.datetime(2023, 6, 3, 14, 14, 44): {'price': 10029,
                                                        'volume': 32},
            datetime.datetime(2023, 6, 3, 15, 14, 6): {'price': 10748,
                                                       'volume': 25}}}

 

 

 

 

 

2. 전체 체결데이터 -> OHLCV로 변환하기

 

 

10,000건의 랜덤 체결 데이터 생성 후 OHLCV로 변환하기

# 전체 체결데이터를 DataFrame으로 변환 후 Resample
df = pd.DataFrame.from_dict(tick_data['000000'], orient='index')
open = df['price'].resample('1min').first().rename('open')
high = df['price'].resample('1min').max().rename('high')
low = df['price'].resample('1min').min().rename('low')
close = df['price'].resample('1min').last().rename('close')
volume = df['volume'].resample('1min').sum().rename('volume')
tdf = pd.concat([open, high, low, close, volume], axis=1)
print(tdf)

 

                      open   high    low  close  volume
2023-06-03 09:00:00  10246  10980  10034  10193     568
2023-06-03 09:01:00  10581  10998  10078  10078     521
2023-06-03 09:02:00  10357  10956  10120  10374     666
2023-06-03 09:03:00  10223  10923  10022  10844     606
2023-06-03 09:04:00  10936  10941  10013  10802     488
...                    ...    ...    ...    ...     ...
2023-06-03 15:40:00  10971  10996  10187  10996     741
2023-06-03 15:41:00  10449  10965  10005  10443     650
2023-06-03 15:42:00  10460  10950  10055  10950     594
2023-06-03 15:43:00  10905  10992  10016  10107     685
2023-06-03 15:44:00  10572  10947  10029  10099     473

 

 

 

 

 

3. 특정 시간대의 체결데이터로만 OHLCV계산

 

 

전체 체결데이터가 아닌 특정 시간대 동안 체결된 가격들에서 open, high, low, close, volume을 계산하는 방법

# 전체 체결데이터 중에서 일부만 추출 (start 이상 + end 미만)
start = datetime(2023, 6, 3, 15, 40)
end = datetime(2023, 6, 3, 15, 45)
new_dict = {key: value for key, value in tick_data['000000'].items() if start <= key < end}

# 해당 데이터에서 OHLCV값만 추출후 딕셔너리 반환
price_list = [item['price'] for item in new_dict.values()]
open = new_dict[min(new_dict)]['price']
high = max(price_list)
low = min(price_list)
close = new_dict[max(new_dict)]['price']
volume = sum([item['volume'] for item in new_dict.values()])
ohlcv_dict = {start: {'open': open, 'high': high, 'low': low, 'close': close, 'volume': volume}}
print(ohlcv_dict)

 

[실행결과]

{'open': 10971, 'high': 10996, 'low': 10005, 'close': 10099, 'volume': 3143}