数字货币STOCHRSI指标python计算实现

接上一篇,继macd,kdj,rsi,sar等指标后,接下来研究STOCHRSI指标,这个指标结合了rsi和kdj指标的计算方法。

在网上找到了一些 关于这个指标的计算公式,但代码实现起来网上模板很少,以下是研究大半天的成果,希望对大家有帮助,

数据来源于okex交易所的永续合约,btc_usdt,30min线,参数可以自己设定,

计算结果跟okex的TradingView一致,可自行检验。

"""
LC := REF(CLOSE,1); //REF(C,1) 上一周期的收盘价
RSI:=SMA(MAX(CLOSE-LC,0),N,1)/SMA(ABS(CLOSE-LC),N,1) *100;
%K:     MA(RSI-LLV(RSI,M),P1)/MA(HHV(RSI,M)-LLV(RSI,M),P1)*100;  LLV(l,60)表示:检索60天内的最低价,可适应于检索任何股票
%D:MA(%K,P2);

LC := REF(CLOSE,1);
RSI:=SMA(MAX(CLOSE-LC,0),N,1)/SMA(ABS(CLOSE-LC),N,1) *100;
STOCHRSI:MA(RSI-LLV(RSI,M),P1)/MA(HHV(RSI,M)-LLV(RSI,M),P1)*100;

"""

import numpy as np
np.set_printoptions(suppress=True)   # 取消科学计数法
import pandas as pd
import talib
import requests
import time
import json


# 计算公式
def StochRSI(close, m, p):
    RSI = talib.RSI(np.array(close), timeperiod=m)
    RSI = pd.DataFrame(RSI)
    LLV = RSI.rolling(window=m).min()
    HHV = RSI.rolling(window=m).max()
    stochRSI = (RSI - LLV) / (HHV - LLV) * 100
    stochRSI = talib.MA(np.array(stochRSI[0]), p)
    # stochRSI = np.around(stochRSI, decimals=4, out=None)
    # print(np.array(stochRSI))
    fastk = talib.MA(np.array(stochRSI), p)
    fastk = np.around(fastk, decimals=4, out=None)
    # fastd = talib.MA(np.array(fastk), p)
    dif = stochRSI-fastk
    # print(dif)
    return stochRSI,fastk


# 获取okex永续合约k线数据
def get_klinedata(coin, granularity):
    res = requests.get("https://www.okex.me/api/swap/v3/instruments/{}-USD-SWAP/candles?granularity={}".format(coin.upper(), granularity))
    klinedata = json.loads(res.content.decode())[::-1]
    for i in klinedata:
        t = i[0].replace("T", " ").replace(".000Z", "")
        timeStruct = time.strptime(t, "%Y-%m-%d %H:%M:%S")
        timeStamp = int(time.mktime(timeStruct)) + 60 * 60 * 8
        i[0] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timeStamp))
    return klinedata


if __name__ == '__main__':

    klinedata = get_klinedata("btc", 1800)
    close = [float(i[4]) for i in klinedata]
    stochRSI, fastk = StochRSI(close, 14, 3)
    print(stochRSI, "\n\n",fastk)
 

你可能感兴趣的:(python)