Stoch RSI is broken
For some reason I'm getting completely wrong numbers.
fastk, fastd = talib.STOCHRSI(candles.close.values, timeperiod=14, fastk_period=3, fastd_period=3)
Any ideas why it might not work?
Hard to tell without any price data or what values you expect versus the ones you get.
Do other indicators work on your computer?
On Apr 27, 2018, at 5:08 AM, Matic Conradi [email protected] wrote:
For some reason I'm getting completely wrong numbers.
fastk, fastd = talib.STOCHRSI(data.close.values, timeperiod=14, fastk_period=3, fastd_period=3)
It looks all good but it isn't. Any ideas?
— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub, or mute the thread.
Everything else works. RSI is correct. I feed in BTC/USD data from CCXT library. They are way off from what's actually going on.
Here's an example (BTC/USD [XBTUSD] from BitMEX):
5min close value candle data (last 20 candles): [9205, 9222.5, 9226.5, 9235, 9227.5, 9228.5, 9226, 9234.5, 9241, 9237, 9255, 9249, 9241.5, 9230.5, 9256.5, 9255.5, 9254.5, 9268, 9248, 9258]
D: [37.57962284, 70.91295617, 92.11272073, 100, 82.41736032, 57.1553351, 23.82200176, 41.40464144, 66.66666667, 85.20923078, 85.20923078, 76.03295412, 57.49039001, 24.15705667, 33.33333333, 65.5339434, 65.5339434, 65.5339434, 33.33333333, 50.08188329]
K: [76.33816218, 100, 100, 100, 47.25208097, 24.21392432, 0, 100, 100, 55.62769234, 100, 72.47117002, 0, 0, 100, 96.60183021, 0, 100, 0, 50.24564987]
The fastK is way off, same for fastD
Any updates? Do you need aditional info/data?
I've been trying to get it working but came to the conclusion that Stochastic (talib.STOCH(...)) doesn't work either. RSI is 100% correct, so is the price I get from the exchange.
Why not try and get a pure python version working with expected output and then we can figure out what you're looking for. Seems like it's more likely you are defining it differently than TA-Lib.
https://sourceforge.net/p/ta-lib/code/HEAD/tree/trunk/ta-lib/c/src/ta_func/ta_STOCHRSI.c
This might be a little different than you expect, and I didn't really debug or test it, but posting here for discussion.
import numpy as np
import pandas as pd
def STOCH(h, l, c, fastk_period, slowk_period, slowd_period):
hh = pd.rolling_max(h, fastk_period, min_periods=fastk_period)
ll = pd.rolling_min(l, fastk_period, min_periods=fastk_period)
fast_k = 100 * (c - ll) / (hh - ll)
slow_k = pd.ewma(fast_k, span=slowk_period, min_periods=slowk_period)
slow_d = pd.ewma(slow_k, span=slowd_period, min_periods=slowd_period)
return slow_k, slow_d
def RS(c, n):
diffs = pd.rolling_apply(c, 2, lambda x: x[-1] - x[0], min_periods=1)
ups = pd.rolling_apply(diffs, n, lambda x: np.sum(x[x > 0]), min_periods=n)
downs = pd.rolling_apply(diffs, n, lambda x: -np.sum(x[x < 0]), min_periods=n)
rs = ups / downs
rs[downs == 0] = 0
return rs
def RSI(c, n):
rs = RS(c, n)
rsi = 100 - (100 / (1 + rs))
return rsi
def STOCHRSI(c, timeperiod, fastk_period, fastd_period):
rsi = RSI(c, timeperiod)
return STOCH(rsi, rsi, rsi, timeperiod, fastk_period, fastd_period)
I should also note, you can try the TulipIndicators and see if that gives you results you expect.
I got it working by using Tulip indicators and calling fastk, fastd = ti.stoch(rsi, rsi, rsi, 14, 3, 3), still can't get it to work with TA-Lib though.
I have a similar issue with the normal RSI. I can recognize the ups and downs but the magnitudes are quite different. Do you mind sharing your RSI implementation?
You can browse the underlying TA-Lib C library if you want:
https://github.com/TA-Lib/ta-lib/blob/master/src/ta_func/ta_RSI.c
If anyone wants to provide a test case for what they expect and what they get, I could look into it. I suspect a definitional difference, either smoothing related or similar.
I looked into the definition but that goes over my head. I only recently started programming. I also looked into smoothing and but from the RSI settings on the exchanges I can see no smoothing function.
The code here is supposed to fetch the last 900 hours of data for BTC-EUR pairing on coinbase (no api-keys required) and plot it. I also tested the "stockstats" lib with the same result and I use tradingview.com for compare my RSI values.
`import pandas as pd import stockstats import json import coinbase import matplotlib.pyplot as plt import requests as req import numpy as np import mpl_finance import datetime as dt import talib as ta import time
#initialize the dates and variables list_a = [] start_time = dt.datetime.strptime("2018-10-04",'%Y-%m-%d') end_time = dt.datetime.strptime("2000-01-01",'%Y-%m-%d') minus_300 = -288 #the coinbase api allows max 300 values per call i = 0 result_array = np.empty([0, 6])
while True:
print(i)
end_time = start_time
start_time = start_time + dt.timedelta(hours=minus_300)
start_time = start_time.strftime('%Y-%m-%d') #converts timestamp to normal time for the link to work as a string
end_time = end_time.strftime('%Y-%m-%d')
#these variables build the url for the api call
coinbase_url_1 = "https://api.pro.coinbase.com/products/BTC-EUR/candles?granularity="
granularity = "3600"
coinbase_url_2 = "&start="
coinbase_url_3 = "&end="
print(coinbase_url_1+granularity+coinbase_url_2+start_time+coinbase_url_3+end_time)
url_full = coinbase_url_1+granularity+coinbase_url_2+start_time+coinbase_url_3+end_time
api_call = req.get(url_full)
data = json.loads(api_call.content.decode('utf-8')) #json object to python list
candles = np.array(data) #python list to numpy array
print(candles.shape)
result_array = np.append(result_array, candles, axis=0) #appends each new datablock to the existing array
#print(result_array)
print("result_shape: ", result_array.shape)
print("length: ",len(result_array))
#print(type(candles))
#print("length: ",len(candles))
start_time = dt.datetime.strptime(start_time,'%Y-%m-%d') #converts timeformat back to work with timedelta
end_time = dt.datetime.strptime(end_time,'%Y-%m-%d')
i = i+1
time.sleep(0.35) #3 api calls per sec
if i == 3:
break
normal_time = np.vectorize(dt.datetime.fromtimestamp)(result_array[:,0]) #normal_time = dt.datetime.strptime(result_array[:,0],'%Y-%m-%d') #print(normal_time) #open_data = candles[:,3] #high_data = candles[:,2] #low_data = candles[:,1] close_data = result_array[:,4] #print("close_data: ",close_data) print("length: ",len(close_data))
rsi_graph = ta.RSI(close_data, timeperiod=14) #print (rsi_graph)
print(min(normal_time), max(normal_time))
plt.plot(normal_time, rsi_graph) plt.xticks(rotation=45) plt.ylim(0, 100) plt.xlabel('time (days)') plt.ylabel('RSI') plt.hlines(y=70, xmin=min(normal_time), xmax=max(normal_time), linestyles='dashed') plt.hlines(y=30, xmin=min(normal_time), xmax=max(normal_time), linestyles='dashed') plt.show()
`
Hello,
I'm having the same problem over here ! Is there any progress on the issue ?
Alex
yes, turned out that the way i created the array for calculating the rsi was in reverse order. after i reversed it the rsi looked excatly like i was supposed to
I'm using the abstract API, the numbers are nonsensical while normal RSI is giving the good results so I guess I'm not doing anything wrong. Is there something I can contribute to to help?
the rsi numbers are nonsensical or the base data?
The code by Sungod3000 above is not showing correctly. This works in Spyder if you have the correct packages installed:
import pandas as pd
import stockstats
import json
import coinbase
import matplotlib.pyplot as plt
import requests as req
import numpy as np
import mpl_finance
import datetime as dt
import talib as ta
import time
#initialize the dates and variables
list_a = []
start_time = dt.datetime.strptime("2018-10-04",'%Y-%m-%d')
end_time = dt.datetime.strptime("2000-01-01",'%Y-%m-%d')
minus_300 = -288 #the coinbase api allows max 300 values per call
i = 0
result_array = np.empty([0, 6])
while True:
print i
end_time = start_time
start_time = start_time + dt.timedelta(hours=minus_300)
start_time = start_time.strftime('%Y-%m-%d') #converts timestamp to normal time for the link to work as a string
end_time = end_time.strftime('%Y-%m-%d')
#these variables build the url for the api call
coinbase_url_1 = "https://api.pro.coinbase.com/products/BTC-EUR/candles?granularity="
granularity = "3600"
coinbase_url_2 = "&start="
coinbase_url_3 = "&end="
print(coinbase_url_1+granularity+coinbase_url_2+start_time+coinbase_url_3+end_time)
url_full = coinbase_url_1+granularity+coinbase_url_2+start_time+coinbase_url_3+end_time
api_call = req.get(url_full)
data = json.loads(api_call.content.decode('utf-8')) #json object to python list
candles = np.array(data) #python list to numpy array
print(candles.shape)
result_array = np.append(result_array, candles, axis=0) #appends each new datablock to the existing array
#print(result_array)
print("result_shape: ", result_array.shape)
print("length: ",len(result_array))
#print(type(candles))
#print("length: ",len(candles))
start_time = dt.datetime.strptime(start_time,'%Y-%m-%d') #converts timeformat back to work with timedelta
end_time = dt.datetime.strptime(end_time,'%Y-%m-%d')
i = i+1
time.sleep(0.35) #3 api calls per sec
if i == 3:
break
normal_time = np.vectorize(dt.datetime.fromtimestamp)(result_array[:,0])
#normal_time = dt.datetime.strptime(result_array[:,0],'%Y-%m-%d')
#print(normal_time)
#open_data = candles[:,3]
#high_data = candles[:,2]
#low_data = candles[:,1]
close_data = result_array[:,4]
#print("close_data: ",close_data)
print("length: ",len(close_data))
rsi_graph = ta.RSI(close_data, timeperiod=14)
#print (rsi_graph)
print(min(normal_time), max(normal_time))
plt.plot(normal_time, rsi_graph)
plt.xticks(rotation=45)
plt.ylim(0, 100)
plt.xlabel('time (days)')
plt.ylabel('RSI')
plt.hlines(y=70, xmin=min(normal_time), xmax=max(normal_time), linestyles='dashed')
plt.hlines(y=30, xmin=min(normal_time), xmax=max(normal_time), linestyles='dashed')
plt.show()
i.e.

yes in order to make that work you need to reverse -> "close_data [::-1]"
the rsi numbers are nonsensical or the base data?
They're nonsensical on my data (BTC prices from Binance) using Stoch RSI, while they are totally valid with RSI.
Is there any way to help the maintainers figure it out ?
Do you have a test case showing what you expect versus what you get? I suspect it has to do more with definitional differences (or like the other commenter, data in backwards chronological order instead of forwards).
We have also seen problems with small prices near zero with some crypto currencies.
Unless the Function API works but Abstract API does not and then maybe it’s being used differently or is a bug.
I can look more later today or tomorrow.
On Nov 28, 2018, at 12:07 PM, Alex Toussaint [email protected] wrote:
the rsi numbers are nonsensical or the base data?
They're nonsensical on my data (BTC prices from Binance) using Stoch RSI, while they are totally valid with RSI.
Is there any way to help the maintainers figure it out ?
— You are receiving this because you commented. Reply to this email directly, view it on GitHub, or mute the thread.
Hello,
The code where I'm using it is quite huge, I've used the quickfix provided here :
I got it working by using Tulip indicators and calling
fastk, fastd = ti.stoch(rsi, rsi, rsi, 14, 3, 3), still can't get it to work with TA-Lib though.
I'll give you a "working" example of the bug as soon as I can, thanks for the help !
Alex
I got it working by using Tulip indicators and calling
fastk, fastd = ti.stoch(rsi, rsi, rsi, 14, 3, 3), still can't get it to work with TA-Lib though.
are the values exactly same as in the trading view ? For me it did not work , I want to get the values exactly same as trading view but none of the libraries work,