Git Product home page Git Product logo

trendln's Introduction

trendln

Support and Resistance Trend lines Calculator for Financial Analysis

PyPI - Python Version PyPI - Version PyPI - Status PyPI - Downloads PyPI - License PyPI - Implementation Latest push build on default branch GitHub stars

Note

This library can calculate and plot trend lines for any time series, not only for its primary intended purpose of financial analysis.

Changelog »


==> Check out this article on Programmatic Identification of Support/Resistance Trend lines with Python or alternatively here for details on how the library and its features are implemented and work.


Quick Start

Calculation Only

The calc_support_resistance function will calculate all support and resistance information including local extrema, average and their trend lines using several different methods:

import trendln
# this will serve as an example for security or index closing prices, or low and high prices
import yfinance as yf # requires yfinance - pip install yfinance
tick = yf.Ticker('^GSPC') # S&P500
hist = tick.history(period="max", rounding=True)
h = hist[-1000:].Close
mins, maxs = trendln.calc_support_resistance(h)
minimaIdxs, pmin, mintrend, minwindows = trendln.calc_support_resistance((hist[-1000:].Low, None)) #support only
mins, maxs = trendln.calc_support_resistance((hist[-1000:].Low, hist[-1000:].High))
(minimaIdxs, pmin, mintrend, minwindows), (maximaIdxs, pmax, maxtrend, maxwindows) = mins, maxs

Documentation for usage:

(minimaIdxs, pmin, mintrend, minwindows), (maximaIdxs, pmax, maxtrend, maxwindows) = \
	trendln.calc_support_resistance(
	# list/numpy ndarray/pandas Series of data as bool/int/float and if not a list also unsigned
	# or 2-tuple (support, resistance) where support and resistance are 1-dimensional array-like or one or the other is None
	# can calculate only support, only resistance, both for different data, or both for identical data
	h,

	# METHOD_NAIVE - any local minima or maxima only for a single interval (currently requires pandas)
	# METHOD_NAIVECONSEC - any local minima or maxima including those for consecutive constant intervals (currently requires pandas)
	# METHOD_NUMDIFF (default) - numerical differentiation determined local minima or maxima (requires findiff)
	extmethod = METHOD_NUMDIFF,
	
	# METHOD_NCUBED - simple exhuastive 3 point search (slowest)
	# METHOD_NSQUREDLOGN (default) - 2 point sorted slope search (fast)
	# METHOD_HOUGHPOINTS - Hough line transform optimized for points
	# METHOD_HOUGHLINES - image-based Hough line transform (requires scikit-image)
	# METHOD_PROBHOUGH - image-based Probabilistic Hough line transform (requires scikit-image)
	method=METHOD_NSQUREDLOGN,
	
	# window size when searching for trend lines prior to merging together
	window=125,
	
	# maximum percentage slope standard error
	errpct = 0.005,
	
	# for all METHOD_*HOUGH*, the smallest unit increment for discretization e.g. cents/pennies 0.01
	hough_scale=0.01,
	
	# only for METHOD_PROBHOUGH, number of iterations to run
	hough_prob_iter=10,
	
	# sort by area under wrong side of curve, otherwise sort by slope standard error
	sortError=False,
	
	# accuracy if using METHOD_NUMDIFF for example 5-point stencil is accuracy=3
	accuracy=1)
# if h is a 2-tuple with one value as None, then a 2-tuple is not returned, but the appropriate tuple instead
# minimaIdxs - sorted list of indexes to the local minima
# pmin - [slope, intercept] of average best fit line through all local minima points
# mintrend - sorted list containing (points, result) for local minima trend lines
	# points - list of indexes to points in trend line
	# result - (slope, intercept, SSR, slopeErr, interceptErr, areaAvg)
		# slope - slope of best fit trend line
		# intercept - y-intercept of best fit trend line
		# SSR - sum of squares due to regression
		# slopeErr - standard error of slope
		# interceptErr - standard error of intercept
		# areaAvg - Reimann sum area of difference between best fit trend line
		#   and actual data points averaged per time unit
# minwindows - list of windows each containing mintrend for that window

# maximaIdxs - sorted list of indexes to the local maxima
# pmax - [slope, intercept] of average best fit line through all local maxima points
# maxtrend - sorted list containing (points, result) for local maxima trend lines
	#see for mintrend above
# maxwindows - list of windows each containing maxtrend for that window

The get_extrema function will calculate all of the local minima and local maxima without performing the full trend line calculation.

minimaIdxs, maximaIdxs = trendln.get_extrema(hist[-1000:].Close)
maximaIdxs = trendln.get_extrema((None, hist[-1000:].High)) #maxima only
minimaIdxs, maximaIdxs = trendln.get_extrema((hist[-1000:].Low, hist[-1000:].High))

Documentation for usage:

minimaIdxs, maximaIdxs = trendln.get_extrema(
	h,
	extmethod=METHOD_NUMDIFF,
	accuracy=1)
# parameters and results are as per defined for calc_support_resistance

Plotting Calculations

The plot_support_resistance function will calculate and plot the average and top 2 support and resistance lines, along with marking extrema used with a maximum history length, and otherwise identical arguments to the calculation function.

fig = trendln.plot_support_resistance(hist[-1000:].Close) # requires matplotlib - pip install matplotlib
plt.savefig('suppres.svg', format='svg')
plt.show()
plt.clf() #clear figure

Documentation for usage:

fig = trendln.plot_support_resistance(
	hist, #as per h for calc_support_resistance
	xformatter = None, #x-axis data formatter turning numeric indexes to display output
	  # e.g. ticker.FuncFormatter(func) otherwise just display numeric indexes
	numbest = 2, #number of best support and best resistance lines to display
	fromwindows = True, #draw numbest best from each window, otherwise draw numbest across whole range
	pctbound = 0.1, # bound trend line based on this maximum percentage of the data range above the high or below the low
	extmethod = METHOD_NUMDIFF,
	method=METHOD_NSQUREDLOGN,
	window=125,
	errpct = 0.005,
	hough_prob_iter=10,
	sortError=False,
	accuracy=1)
# other parameters as per calc_support_resistance
# fig - returns matplotlib.pyplot.gcf() or the current figure

The plot_sup_res_date function will do the same as plot_support_resistance with help for nice formatting of dates based on a pandas date index.

idx = hist[-1000:].index
fig = trendln.plot_sup_res_date((hist[-1000:].Low, hist[-1000:].High), idx) #requires pandas
plt.savefig('suppres.svg', format='svg')
plt.show()
plt.clf() #clear figure

Documentation for usage:

fig = trendln.plot_sup_res_date( #automatic date formatter based on US trading calendar
	hist, #as per h for calc_support_resistance
	idx, #date index from pandas
	numbest = 2,
	fromwindows = True,
	pctbound = 0.1,
	extmethod = METHOD_NUMDIFF,
	method=METHOD_NSQUREDLOGN,
	window=125,
	errpct = 0.005,
	hough_scale=0.01,
	hough_prob_iter=10,
	sortError=False,
	accuracy=1)
# other parameters as per plot_support_resistance

Finally, for the above mentioned article, some figures were generated for reference material, while others use the library to demonstrate how it works. These can be generated as well:

trendln.plot_sup_res_learn('.', hist)

Documentation for usage:

trendln.plot_sup_res_learn( #draw learning figures, included for reference material only
	curdir, #base output directory for png and svg images, will be saved in 'data' subfolder
	hist) #pandas DataFrame containing Close and date index

Example output of plotting support resistance

Installation

Install trendln using pip:

$ pip install trendln --upgrade --no-cache-dir

Install trendln using conda:

$ conda install -c GregoryMorse trendln

Installation sanity check:

import trendln
#requires yfinance library install, not a package requirement, but used to assist with sanity check
#pip install yfinance
directory = '.' # a 'data' folder will be created here if not existing to store images
trendln.test_sup_res(directory) #simple tests that all methods are executing correct, assertion or other error indicates problem

Requirements

  • Python >= 2.7, 3.4+
  • numpy >= 1.15
  • findiff >= 0.7.0 (if using default numerical differentiation method)
  • scikit-image >= 0.14.0 (if using image-based Hough line transform or its probabilistic variant)
  • pandas >= 0.23.1 (if using date plotting function, or using naive minima/maxima methods)
  • matplotlib >= 2.2.4 (if using any plotting function)

License

trendln is distributed under the MIT License. See the LICENSE file in the release for details.

Support

Any questions, issues or ideas can kindly be submitted for review.

Gregory Morse [email protected]

trendln's People

Contributors

gregorymorse avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

trendln's Issues

Change plot size

good job!

Is there a way to change plot size?
maybe a parameter one can set?

Thanks!

Question about patterns

First of all, i wanted to thank you for taking your time to make the article (i found this repository there) and to release this awesome library, it's incredibly useful and i'm learning a lot from it.

Before finding your article, i was dealing with a quite complicated task: detecting patterns from OHLC data, such as flags, pennants, double bottoms and so on.
Just like you did, i started from computing local minima and maxima from my data, to do that i used the following function:
df['max'] = df.iloc[argrelextrema(df.Open.values, np.greater_equal, order=n)[0]]['Open']

where df is the dataframe that will store the OHLC data. From there i've been defining patterns on my own, now i'm trying to learn pattern detection to try and find patterns defined by me on other dataset, but i'm ecountering a lot of problems. I was wondering if you are planning to cover that part too on your library, or if you have any tip on how to do that. Keep up your awesome work.

Change OHLC to yfinance format

Dear developer, thank you for sharing your code, It is very impressive.

I want to use it in cryptocurrencies, so I have an issue trying to change my Pandas format (Dataframe) with OHLC to the format required in yfinance.

I have replazed

tick = yf.Ticker('^GSPC') # S&P500
hist = tick.history(period="max", rounding=True)
h = hist[-1000:].Close

for

candles = exchange.fetch_ohlcv ('BTC/USDT', '4h')
df = pd.DataFrame(candles,columns=['Date','Open','High','Low','Close','Volume'])
df['Date'] = df['Date'].apply(lambda date: pd.Timestamp(time.ctime(date/1000.)))
h = df['Close']
hist = df

It is working, but I do not know if I done correctly, what do you think?

numbest yields additional trendlines; feature question/suggestion

great library, big thanks for sharing!

1 observation: when numbest is set to 1, I get 2 trendlines for both support and resistance, ie when set to 2 I get 3, and 3 yields ie 5 lines. Not sure if this is a bug or if I misunderstand the logic

Also wanted to ask (possible feature request):
is it possible to not display the average support and average resistance lines?
and
is it possible to set the sensitivity of the pivot identification so that ie it would only isolate more significant turning points?

Example test code

Can you share an example code file? Because when I try to run I saw "NameError: name 'h' is not defined"

Example

first:
mins, maxs = calc_support_resistance(hist[-1000:].Close)

must be changed at:

values = calc_support_resistance(hist[-1000:].Close)

because FCE return this:
return (extremaIdxs[0], pmin, mintrend, minwindows), (extremaIdxs[1], pmax, maxtrend, maxwindows)

other get error:

ValueError: too many values to unpack (expected 2)

METHOD

I trying the method, and METHOD_NAIVE and METHOD_NAIVECONSEC is look like identicals.

If you want to see, I send the jupyter file in my fork.

Milan

Feature Request : Need Support and Resistance points for a given Days close price

Hi Gregory,

First of all, let me congratulate you on the splendid job that you have done to identify support and resistance. Now I have one feature request, if possible can you please add :

  1. One function which will take the day and its close price as an input and will return closest support as support1, support2, support3 etc which are basically the extension of the lines that are drawn on the plot. Also if possible the strength of the support/resistance from how many dots it connect.

  2. Likewise the same for resistance.

  3. Risk to reward rations with these support and resistances.

This feature will help us in :

  • Identifying the trades with our choice of risk to reward ratios.
  • Identifying the breakouts when it breaks the resistance and identify the target as the next resistance line.

Thanks a lot in advance.

Regards,
Arka

FinDiff object error

I hope you can help, I get an error when I run the sample code from example.py
I will get this error:
"FinDiff objects can only be applied to arrays or evaluated(!) functions returning arrays") from err

I will use Python 2.7.
I hope someone can help me to fix this

code from example.py

import trendln
import matplotlib.pyplot as plt

import yfinance as yf # requires yfinance - pip install yfinance
tick = yf.Ticker('^GSPC') # S&P500
hist = tick.history(period="max", rounding=True)
mins, maxs = trendln.calc_support_resistance(hist[-1000:].Close)
minimaIdxs, pmin, mintrend, minwindows = trendln.calc_support_resistance((hist[-1000:].Low, None)) #support only
mins, maxs = trendln.calc_support_resistance((hist[-1000:].Low, hist[-1000:].High))
(minimaIdxs, pmin, mintrend, minwindows), (maximaIdxs, pmax, maxtrend, maxwindows) = mins, maxs
minimaIdxs, maximaIdxs = trendln.get_extrema(hist[-1000:].Close)
maximaIdxs = trendln.get_extrema((None, hist[-1000:].High)) #maxima only
minimaIdxs, maximaIdxs = trendln.get_extrema((hist[-1000:].Low, hist[-1000:].High))
fig = trendln.plot_support_resistance(hist[-1000:].Close) # requires matplotlib - pip install matplotlib
plt.savefig('suppres.svg', format='svg')
plt.show()
plt.clf() #clear figure
fig = trendln.plot_sup_res_date((hist[-1000:].Low, hist[-1000:].High), hist[-1000:].index) #requires pandas
plt.savefig('suppres.svg', format='svg')
plt.show()
plt.clf() #clear figure
curdir = '.'
trendln.plot_sup_res_learn(curdir, hist)

Getting error for minimaIdxs, pmin, mintrend, minwindows

import trendln
from nsepy import get_history
from datetime import datetime
import matplotlib.pyplot as plt

start_date = datetime(2020, 1, 1)
end_date = datetime(2021, 2, 10)
stock_history = get_history(symbol="SBIN", start=start_date, end=end_date)
minvals, maxvals = trendln.calc_support_resistance(stock_history['Close'], accuracy=2)
minimaIdxs, pmin, mintrend, minwindows = trendln.calc_support_resistance(stock_history['Low'], None) #support only

Getting error:
ValueError: not enough values to unpack (expected 4, got 2)
Backend TkAgg is interactive backend. Turning interactive mode on.

Numpy and Floats

Line 587 for Hough Points passes a float into a function that requires an integer on newer versions of numpy, tested on numpy 1.19.4

Getting horizontal levels

Hi! I was looking for a library that does exactly this and i was delighted to find your article. I was wondering if there is a way to detect and plot only horizontal support/resistance levels instead of trendlines, as shown in this image. Thank you for what you are doing.

NameError: name 'METHOD_NCUBED' is not defined

Hello,

I'm not that great with Python, more of a JS dev, so I don't know if this is correct?

When trying to pass in the parameters method, extmethod without quotes results in error. I suggest a fix.

trendln.plot_support_resistance(
            hist[-1000:].Close, method="METHOD_PROBHOUGH")

Then on lines 950 - 960 of init.py


    if method == "METHOD_NCUBED":
        trendmethod = get_trend
    elif method == "METHOD_NSQUREDLOGN":
        trendmethod = get_trend_opt
    elif method == "METHOD_HOUGHPOINTS":
        trendmethod = houghpt
    # pip install scikit-image
    elif method == "METHOD_HOUGHLINES":
        trendmethod = hough
    elif method == "METHOD_PROBHOUGH":
        trendmethod = prob_hough

Getting a value error when calculating support and resistance

Hi,

I am trying to calculate support and resistance levels for a set of closing prices. These are in a pandas data frame. When I run my code, I get the following error.

Traceback (most recent call last):
File "speak_candle_pattern.py", line 112, in
sr_frame=calculate_support_resistance(ema_frame)
File "speak_candle_pattern.py", line 95, in calculate_support_resistance
minvals, maxvals = trendln.calc_support_resistance(df['close'],accuracy=1)
File "/home/pranav/.virtualenvs/stocks/lib/python3.7/site-packages/trendln/init.py", line 737, in calc_support_res
istance
extremaIdxs = get_extrema(h, extmethod, accuracy)
File "/home/pranav/.virtualenvs/stocks/lib/python3.7/site-packages/trendln/init.py", line 456, in get_extrema
minFunc, maxFunc, numdiff_extrema = get_minmax(h)
File "/home/pranav/.virtualenvs/stocks/lib/python3.7/site-packages/trendln/init.py", line 442, in get_minmax
mom, momacc = d_dx(clarr), d2_dx2(clarr)
File "/home/pranav/.virtualenvs/stocks/lib/python3.7/site-packages/findiff/operators.py", line 79, in call
return self.apply(rhs, *args, **kwargs)
File "/home/pranav/.virtualenvs/stocks/lib/python3.7/site-packages/findiff/operators.py", line 94, in apply
return self.pds(rhs, *args, **kwargs)
File "/home/pranav/.virtualenvs/stocks/lib/python3.7/site-packages/findiff/diff.py", line 216, in call
return self.apply(rhs, *args, **kwargs)
File "/home/pranav/.virtualenvs/stocks/lib/python3.7/site-packages/findiff/diff.py", line 275, in apply
return self.diff(u, h, acc)
File "/home/pranav/.virtualenvs/stocks/lib/python3.7/site-packages/findiff/diff.py", line 287, in diff
coefs = coefficients(self.order, acc)
File "/home/pranav/.virtualenvs/stocks/lib/python3.7/site-packages/findiff/coefs.py", line 32, in coefficients
_validate_acc(acc)
File "/home/pranav/.virtualenvs/stocks/lib/python3.7/site-packages/findiff/coefs.py", line 207, in _validate_acc
raise ValueError('Accuracy order acc must be positive EVEN integer')
ValueError: Accuracy order acc must be positive EVEN integer

I am unable to determine what I am doing wrong. My complete code is below.

def calculate_support_resistance(df):
minvals, maxvals = trendln.calc_support_resistance(df['close'],accuracy=1)
df["Resistance"]=maxvals
df['Support']=minvals
return df

Quote-Equity-HDFCBANK-EQ-05-01-2020-to-05-01-2021.txt

I am attaching a csv file that contains the data I am using.

unsupported operand type.

i am trying to use your code but getting follow error.

File "tend.py", line 9, in
minimaIdxs, maximaIdxs, pmin, pmax, mintrend, maxtrend, minwindows, maxwindows =calc_support_resistance(hist,extmethod = METHOD_NUMDIFF,method=METHOD_NSQUREDLOGN,window=125,errpct = 0.005,hough_scale=0.01,hough_prob_iter=10,sortError=False)

line 384, in calc_support_resistance
scale = (max_h - min_h) / len_h
TypeError: unsupported operand type(s) for -: 'str' and 'str'

Is it possible to generate trend lines for candlestick bars?

Mostly candlestick bars are used for trading. But this would result in two y points for an x point if you use the upper and lower boundary of the candle body or even four y points if you also add the upper and the lower wick.
Could one get it to work with candlestick bars as well?

Error when using calc_support_resistance with certain parameters

I want to first thank you for this contribution. This library is great.

I am using Python 3.7.5

Using extmethod=METHOD_NAIVECONSEC throws the following error

File "pandas/_libs/tslibs/c_timestamp.pyx", line 236, in 
pandas._libs.tslibs.c_timestamp._Timestamp.__add__
TypeError: Addition/subtraction of integers and integer-arrays with Timestamp is no longer 
supported.  Instead of adding/subtracting `n`, use `n * obj.freq`

Using method=trendln.METHOD_HOUGHPOINTS throws the following error

File "/usr/local/lib/python3.7/site-packages/trendln/__init__.py", line 587, in hough_points
rhos = np.linspace(-diag_len, diag_len, diag_len * 2.0)
File "<__array_function__ internals>", line 6, in linspace
File "/usr/local/lib/python3.7/site-packages/numpy/core/function_base.py", line 121, in linspace
.format(type(num)))
TypeError: object of type <class 'float'> cannot be safely interpreted as an integer.

Furthermore, I'm wondering if you're open to taking feature request like more efficient calculation given stream of data?

Support/Resistance lag

Hello @GregoryMorse , Thank you for the great work.

After several months of playing and using the library, I found that when calculating support and resistance, most of the times it doesn't calculate the last day/minute points. Let say that I'm using daily data and calculating support and resistance on the high/low. Let's also say that last day is having long tail. When calculating S/R, it doesn't show that as a support. However, when we have a new data for the next day, the library shows the long tail as a support point as seen below:

Screen Shot 2020-12-04 at 1 28 19 PM

This is when calculating the S/R until the second to last data points. As you can see there is no support line here.


Screen Shot 2020-12-04 at 1 28 57 PM

This is when calculating S/R with the last data points and now there is a support line for the previous day (long tail)

Can you explain why is this happening? also, is there a way to fix this?

Thank you again for this great library.

Getting trend data into a pandas data frame that has other calculations and using minima and maxima for Fibonacci Retracement

Hi all,

I am trying to get the local minimum and local maximum prices into a pandas data frame. This data frame has other data as well such as the opening, high, low and closing prices, a number of exponential moving averages that I have calculated etc.
To this end, I need a few clarifications.
In terms of data, I have daily price data for a year.

  1. Do the minimaIdxs and maximaIdxs parameters contain indices to each local minimum and maximum price? I am using them as row indices to get to the respective row in the data frame and add the relevant price in its own column.
  2. I want to use Fibonacci Retracement. The local minima and local maxima are perfect for this but the problem I have is that since the number of local maxima and number of local minima are not the same, I am having a hard time finding which is the maximum price and which is the minimum price.

Its possible that I have misunderstood the parameters that calc_support_resistance takes therefore feel free to set me strait.

My code is below.

def calculate_support_resistance(df):
minvals, maxvals = trendln.calc_support_resistance(df['close'],accuracy=2)

(minimaIdxs, pmin, mintrend, minwindows), (maximaIdxs, pmax, maxtrend, maxwindows) = minvals, maxvals
minimums=[None]*len(df['close'].tolist())
maximums=[None]*len(df['close'].tolist())
closing_list=list(df["close"])



for lc in range(0,len(minimaIdxs)):
	minimums[minimaIdxs[lc]]=closing_list[minimaIdxs[lc]]
df['support']=minimums
for lc in range(0,len(maximaIdxs)):
	maximums[maximaIdxs[lc]]=closing_list[maximaIdxs[lc]]
df['resistance']=maximums
return df

unable to get minimaIdxs, maximaIdxs for Lows, Highs

I am looking to capture the minimaIdxs, maximaIdxs from separate Low and High series respectively, but the following line (taken from the read me file):

minimaIdxs, maximaIdxs = trendln.get_extrema(df['Low'], df['High'])

throws the following error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

also should add that each series contains only numbers, ie no nans/missing values

Display output plot as candlesticks

Could you please suggest how I may change the output plot to show candlesticks instead of high and low prices? I've tried a lot of things but couldn't figure out how to make this change. Your help is greatly appreciated.

ValueError: Accuracy order acc must be positive EVEN integer

Minimal example produces this error. Python 3.10.x

import trendln

this will serve as an example for security or index closing prices, or low and high prices

import yfinance as yf # requires yfinance - pip install yfinance
tick = yf.Ticker('^GSPC') # S&P500
hist = tick.history(period="max", rounding=True)
h = hist[-1000:].Close
mins, maxs = trendln.calc_support_resistance(h)
minimaIdxs, pmin, mintrend, minwindows = trendln.calc_support_resistance((hist[-1000:].Low, None)) #support only
mins, maxs = trendln.calc_support_resistance((hist[-1000:].Low, hist[-1000:].High))
(minimaIdxs, pmin, mintrend, minwindows), (maximaIdxs, pmax, maxtrend, maxwindows) = mins, maxs

Code not using object oriented structure

A major refactoring of all the code is planned to make this properly object oriented and handling trend lines in a broader context than financial usage. It will be tested and pushed to the repo for the next release version.

How to continue some support or resistance lines?

Based on the image, sometimes we need to continue a line which is really close to the last point. As an example here we just missed it on chart.

WhatsApp Image 2020-10-29 at 19 32 43

As you can see I just removed the average lines from the outcome :) and I know there is a list of numbers which we draw them as a line to be support or resistance. The only solution is that to continue plot lines by line slope? or there is a better solution?

maxx -

Hi,

this lib is a very good piece. Thanks for the sharing.

I found the bug:
but in the row 699 is var maxx - is not declared.

Milan

Accuracy order acc must be positive EVEN integer

Did any get this erro here?

import trendln

this will serve as an example for security or index closing prices, or low and high prices

import yfinance as yf # requires yfinance - pip install yfinance
import matplotlib.pyplot as plt

tick = yf.Ticker('^GSPC') # S&P500
hist = tick.history(period="max", rounding=True)

h = hist[-1000:].Close
mins, maxs = trendln.calc_support_resistance(h)

ERROR:
File "D:\miniconda3\envs\quant\lib\site-packages\findiff\coefs.py", line 232, in _validate_acc
raise ValueError('Accuracy order acc must be positive EVEN integer')

problem in define "b" variable in __init__ file line 219

Hi
I tried to change the length of "hist " variable in "plot_sup_res_learn" method in init.py file, the default was '2019-10-07' and I changed it to '2019-10-27'. I got an error 'ValueError: cannot convert float NaN to integer'.
when I debug the code I found this line in init.py file line 219 that causes the error. b = hist.Close.iloc[-10] - m * 0 - mn.
some times the value of 'b' becomes 0 and it causes other problems in next lines.
In the following of the line 219, this expression was commented: + height * 0.2
and height was calculated in line 214 and it was also commented

My question is what if I uncomment the line 214 and this expression in line 219 " + height * 0.2"?
How does it affect on the next calculation?

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.