Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Archives
Today
Total
관리 메뉴

Code Habit

[python] bybit-api 사용하여 비트코인 rsi 구하기 본문

카테고리 없음

[python] bybit-api 사용하여 비트코인 rsi 구하기

코드베어 2021. 8. 9. 00:10

rsi는 Relative Strength Index의 약자로 상대강도지수를 뜻한다. 투자에서 사용하는 보조지표로 많이 활용 되는데 보통 30이하는 과매도 70이상은 과매수 구간으로 본다. 물론 모든 보조지표가 정답은 아니지만 단기추세에서 매수/매도의 기준을 잡을 때 사용하면 유리하다. 필자는 보통 매수/매도의 기준지표로 공포지수와 함께 많이 활용한다.

 

bybit에서 제공하는 api로 rsi를 구할수 있다. 매번 거래 사이트에 접속해서 rsi를 분봉별로 체크하는게 귀찮았는데 이를 프로그래밍으로 구현해 자동화 하면 기타 다른 지표들과 함께 데이터를 좀 더 편하고 직관성 있게 볼 수 있는 있다.

 

rsi를 구하는 코드는 다음과 같다.

from pybit import HTTP
import pandas as pd
import time
from datetime import datetime
import calendar

session = HTTP(
    endpoint='https://api.bybit.com', 
)

def rsi_bybit(itv, symbol='BTCUSD'):
    now = datetime.utcnow()
    unixtime = calendar.timegm(now.utctimetuple())
    since = unixtime-itv*60*200;
    response=session.query_kline(symbol='BTCUSD',interval=str(itv),**{'from':since})['result']
    df = pd.DataFrame(response)
    rsi=rsi_calc(df,14).iloc[-1]
    print(rsi)

def rsi_calc(ohlc: pd.DataFrame, period: int = 14):
    ohlc = ohlc['close'].astype(float)
    delta = ohlc.diff()
    gains, declines = delta.copy(), delta.copy()
    gains[gains < 0] = 0
    declines[declines > 0] = 0

    _gain = gains.ewm(com=(period-1), min_periods=period).mean()
    _loss = declines.abs().ewm(com=(period-1), min_periods=period).mean()

    RS = _gain / _loss
    return pd.Series(100-(100/(1+RS)), name="RSI")

# test
while True:
    rsi_bybit(15)
    rsi_bybit(60)    
    rsi_bybit(240)

    time.sleep(1)

bybit에서 제공하는 pybit모듈을 사용하였으며 예제를 돌려보면 매초마다 '15m', '60m', '240m' 분봉기준 RSI가 출력되는 것을 확인할 수 있다.