Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question about supertrend #689

Open
svax974 opened this issue May 11, 2023 · 7 comments
Open

Question about supertrend #689

svax974 opened this issue May 11, 2023 · 7 comments
Labels
info Informational question Further information is requested

Comments

@svax974
Copy link

svax974 commented May 11, 2023

I couldn't figure out how exactly supertrend is working.
How much high/low/closes are needed for that indicator depending on its atr periods number ?
For example, if atr periods is 10 how much history should I pass to it ? 20 values of each ?

Thanks !

@twopirllc twopirllc added question Further information is requested info Informational labels May 13, 2023
@twopirllc
Copy link
Owner

Hi @svax974,

Depends on which version of Pandas TA you are running? main (0.3.14b) or development branch.

Example

import pandas as pd
import pandas_ta as ta

tdf = pd.DataFrame()
tdf = tdf.ta.ticker("qqq", period="1y")
tdf.drop(columns=["Dividends", "Stock Splits"], errors="ignore", inplace=True)

df = tdf.iloc[:11]  # 11 rows/bars minimum for atr_length=10 (development)
df = tdf.iloc[:7]  # 7 rows/bars minimum for atr_length=10 (v0.3.14)

df.ta.supertrend(atr_length=10, append=True)
  • I recommend using the development branch.

Hope this helps! 🍀

Kind Regards,
KJ

@svax974
Copy link
Author

svax974 commented May 14, 2023

Ok, I'm going to follow your advice and will try the dev version.
That one would need ATR+1 input elements, right ?

@svax974
Copy link
Author

svax974 commented May 14, 2023

Oh and from what you wrote, should I understand that the latest data should be first in the array ?
I guess the expected order is the same for all pandas-ta functions, right ?
(I provide data from another source and I'm building the array "manually")

@twopirllc
Copy link
Owner

@svax974

Ok, I'm going to follow your advice and will try the dev version.
That one would need ATR+1 input elements, right ?

With dev yes. But more than that, experiment with different values. Furthermore, indicators will not return anything if the resultant values do not contain "enough" useful data.

Oh and from what you wrote, should I understand that the latest data should be first in the array ?
I guess the expected order is the same for all pandas-ta functions, right ?

The indicators will run the no matter what order the data is in... except for vwap which must be datetime ordered; but it will tell you that.

In general, it is assumed that bars go from oldest to newest. However, if your data comes the other way around... there is a convenience method to reverse the DataFrame that you should run before running indicators.

df = # your newest to oldest ordered data
df = df.ta.reverse() # Data now ordered from oldest to newest

# Now apply indicators ...
df.ta.<indicator>()

Hope that helps! 🍀

@svax974
Copy link
Author

svax974 commented May 14, 2023

Thanks for all the help.
I have my data coming from the oldest ([0]) to the newest ([-1]), so no need to reverse then.
But I'm still confused about how to use that indicator (and some others).

In fact, I'm looking to compute Supertrend for the last candles and for the previous one to check if the trend changed.

What's the best way to do it (with ATR=10 for instance) ?
With each new candle :

  1. Compute Supertrend "st1" on candles[-11:] and "st2" on candles[-12:-1] and compare trend[-1] (trend being the trend array part in the supertrend result having only a last value because computed with 11 values)
  2. Compute Supertrend "st3" on candles[-12:-1] and compare trend[-1] and trend[-2] (having 2 values because computed with 12 values)

I seem to get very different results, sometimes with st1.trend.iat[-1] different from st3.trend.iat[-1] (which seems illogical to me) and sometimes st2.trend.iat[-1] different from st3.trend.iat[-2]...
I hope I'm clear enough in the way I expose my confusion :)

@twopirllc
Copy link
Owner

@svax974

Thanks for all the help.

No worries

I hope I'm clear enough in the way I expose my confusion :)

Do you have sample code to share?

Have to tried help(ta.supertrend)? It returns 4 columns

    Returns:
        pd.DataFrame: SUPERT (trend), SUPERTd (direction),
            SUPERTl (long), SUPERTs (short) columns.

I recommend plotting the results to see if that might help as well.

Last plot shows the direction. So perhaps you can use that to see if the trend change. 🤷🏼‍♂️
Screenshot 2023-05-14 at 12 10 37 PM

KJ

@svax974
Copy link
Author

svax974 commented May 15, 2023

I seem to extract result values correctly, at least I guess.
I'm working "remotely" on an headless computer and my scripts won't need any graphical output so I can't really plot, though I might end to try to.
Also, I might use the term "trend" whereas I'm getting the direction element in fact.

As for the code here is what I do, maybe you'll spot stupid things ;)

I'm running indicators computations in a loop, each loop "advances" one period/candle in time, getting a new latest candle and removing the oldest one from a 'candles' array.
That "candles" is an array of candle data dicts order by timestamp increasing like this : [{'timestamp':t0, 'open': X, 'high': X, 'low': X, 'close': X, 'volume': X}, {'timestamp': t1, ...}, {'timestamp': t2, ...}]).
That "candles" array contains always enough (sometimes more) candles to compute the indicators, but I usually extract only the needed ones in each indicator.

Here are the main two functions I'm using to compute supertrend (almost untouched, only removed commented traces and added some comments) :

        def ind_supertrendswitch(candles, params):
		ret = 0
		atr = int(params['atr']) # Actually atr=10 in my test
		mult = float(params['multiplier']) # mult=3 in my test
                 # Computes supertrend for the previous range of candles (without the last one)
		trend2, lower2, upper2 = getSupertrend( candles[:-1], atr, mult) # Compute a supertrend on 11 candles
		plast = trend2.iat[-1]
                 # Computes supertrend for the latest range of candles
		trend, lower, upper = getSupertrend( candles, atr, mult)
		last = trend.iat[-1]
                 # Computes supertrend for the 2 latest ranges of candles ?
		trend3, lower3, upper3 = getSupertrend2( candles, atr, mult) # Here it will compute supertrend on 12 candles
		plast2 = trend3.iat[-2]
		#print('SUPERTREND SWITCH:')
		#print(trend)
		print("\tSupertrend prelast="+str(plast)+" LAST="+str(last)+" prelast2="+str(plast2))
		if params['side']=='long' and plast==-1 and last==1:
			ret = 1
		# Short, si on switch de trend à la baisse
		if params['side']=='short' and plast==1 and last==-1:
			ret = -1
		return ret

        # getSupertrend2 is the exact same function but "needed = atr_period+2" so that I can get 2 trend values
	def getSupertrend(values2, atr_period=10, multiplier=3.0):
		values = []
		needed = atr_period+1
		if len(values2)<needed:
			raise FunctionnalException("ERROR : not enough candles ("+str(len(values2))+" / "+str(needed)+" needed)")
		else:
			values = values2[-needed:]
		#print( "SUPERTREND - len="+str(len(values)))
		#for candle in values:
		#	print('\t@'+ccFullDate(candle['timestamp']) + ' - ' + str(candle))
		#print("Values[-1] = " + str(values[-1]))
                 #Here I "convert" my candles to a DataFrame
		df = pandas.DataFrame( values, columns = [ 'high', 'low', 'close'])
		#print("DATAFRAME :")
		#print(df)
		sti = ta.supertrend( df['high'], df['low'], df['close'], atr_period, multiplier)
		#print( sti)
		tidx = 'SUPERTd_'+str(atr_period)+'_'+str(round(float(multiplier), 1))
		lidx = 'SUPERTl_'+str(atr_period)+'_'+str(round(float(multiplier), 1))
		hidx = 'SUPERTs_'+str(atr_period)+'_'+str(round(float(multiplier), 1))
		return sti[tidx], sti[lidx], sti[hidx]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
info Informational question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants