본문 바로가기
Finance/Coding

python - 스토캐스틱 ( stochastic ) 구하기 ( pandas )

by ZaRi 2023. 6. 21.

 

 저번에 전고점, 전저점을 알아보았습니다.

 이번에는 파이썬에서 판다스를 활용하여 스토캐스틱을 구해보겠습니다.

 


스토캐스틱 ( stochastic )

먼저 코드는 다음과 같습니다.

 

 

코드

top = df['close'] - df['low'].rolling(window=length).min()
bot = df['high'].rolling(window=length).max() - df['low'].rolling(window=length).min()
K = top / bot * 100 # K 가 스토캐스틱 값

 

함수

# 스토캐스틱
def fstochastic(close, high, low, length):  
    top = close - low.rolling(window=length).min()
    bot = high.rolling(window=length).max() - low.rolling(window=length).min()
    K = top / bot * 100
    return K

 

이 코드를 이용해 스토캐스틱의 % K을 구할 수 있습니다.

그다음 이평선을 사용할 때 썼던 함수를 사용하여 % D까지 구할 수 있습니다.

 

 

 

활용하기

 그러면 데이터를 가져와 적용해 보겠습니다.

 

 

 

import pandas as pd
import ccxt
import fical as fi

symbol = 'BTC/USDT'
timeframe = '1h'
candle = 100

binance = ccxt.binance()
btc_ohlcv = binance.fetch_ohlcv(symbol, timeframe = timeframe, limit = candle)

df = pd.DataFrame(btc_ohlcv, columns=['date', 'open', 'high', 'low', 'close', 'volume'])
df['date'] = pd.to_datetime(df['date'], unit='ms')
df = df.set_index('date')


df['%K'] = fi.fstochastic(df['close'],df['high'],df['low'],14)

# df['%D'] = fi.ma(fi.fstochastic(df['close'],df['high'],df['low'],14),3)  
df['%D'] = fi.fstochastic(df['close'],df['high'],df['low'],14).rolling(window=3).mean()


print(df)

 

fical 모듈에 fstochastic() 함수를 넣어놓았습니다.

우선 실행해서 결과를 봐보겠습니다.

 

 

비트코인의-시가,고가,저가,종가,거래량,%K,%D의-데이터가-출력됨
데이터

 

값이 변하지 않는 상태에서의 정확한 비교를 위해, 가장 최근 값이 아닌 1시간 전의 데이터를 가지고 비교하겠습니다.

%K는 44.64 가 %D는 38.35가 나왔습니다.

트레이딩뷰에서도 봐보겠습니다.

 

 

 

스토캐스틱의-수치가-44.64와-38.35임
스토캐스틱-차트

 

보게 되면 %K는 44.64 그리고 %D는 38.35로 값이 같은 것을 확인할 수 있습니다.

참고) 데이터의 시간이 트레이딩뷰보다 9시간 느린 이유는 데이터는 세계시간을 기준으로 하기 때문.

 

 


이번에 스토캐스틱을 구하는 함수를 만들어 보았습니다. 사람마다 트레이딩을 할 때 자주 사용하는 보조지표는 다르지만 제가 자주 사용했던 지표 중에 하나라 의미가 있었던 것 같네요.

댓글