The calc_support_resistance function calculates local extrema, average trend lines, and individual trend lines using various methods.
Input Data (h):
- A
list, numpy ndarray, or pandas Series of numeric data (bool/int/float). - Or a 2-tuple
(support, resistance) where each element is a 1-dimensional array-like. One element can be None to calculate only one side.
Extrema Methods (extmethod):
METHOD_NAIVE: Local minima/maxima for a single interval (requires pandas).METHOD_NAIVECONSEC: Local minima/maxima including consecutive constant intervals (requires pandas).METHOD_NUMDIFF (default): Numerical differentiation (requires findiff).
Trend Line Methods (method):
METHOD_NSQUREDLOGN (default): 2-point sorted slope search (fast).METHOD_NCUBED: Simple exhaustive 3-point search (slowest).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).
Return Values:
If h is a single array, it returns a 2-tuple: (minima_data, maxima_data).
If h is a 2-tuple with one None value, it returns only the appropriate tuple (either minima or maxima).
Each data tuple contains:
idxs: Sorted list of indexes to the local extrema.p: [slope, intercept] of the average best-fit line.trend: Sorted list of (points, result) for individual trend lines.points: List of indexes in the trend line.result: (slope, intercept, SSR, slopeErr, interceptErr, areaAvg).
windows: List of windows, each containing a trend entry.
If h is a 2-tuple (support, resistance), the function returns two tuples: (minima_data, maxima_data).
Key Parameters:
window: Window size for searching trend lines before merging.errpct: Maximum percentage slope standard error.hough_scale: Smallest unit increment for discretization (e.g., 0.01).hough_prob_iter: Number of iterations for METHOD_PROBHOUGH.sortError: If True, sorts by area under wrong side of curve; otherwise by slope standard error.accuracy: Accuracy for METHOD_NUMDIFF (e.g., 2 for a 5-point stencil).
import trendln
import yfinance as yf
tick = yf.Ticker('^GSPC')
hist = tick.history(period="max", rounding=True)
h = hist[-1000:].Close
# Calculate both support and resistance
mins, maxs = trendln.calc_support_resistance(h)
# Calculate only support using Low prices
minimaIdxs, pmin, mintrend, minwindows = trendln.calc_support_resistance((hist[-1000:].Low, None))
# Calculate using both Low and High prices
mins, maxs = trendln.calc_support_resistance((hist[-1000:].Low, hist[-1000:].High))