trendln

repository·master·Indexed 20 days ago

https://github.com/gregorymorse/trendln

A library for calculating and plotting support and resistance trend lines. It provides tools to find local extrema using numerical differentiation or naive methods and identifies trend lines via various algorithms, including sorted slope search and Hough transforms. Key functions include calc_support_resistance for data analysis, get_extrema for index retrieval, and plot_support_resistance for visualizing results with matplotlib.

Tokens
1.7K
Snippets
5
Records
5
Agent score
22%

What's inside trendln

  1. Install trendln via pip or conda

    master

    You can install trendln using either pip or conda.

    Using pip:

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

    Using conda:

    conda install -c GregoryMorse trendln

    Verify installation: After installing, you can run a sanity check using trendln.test_sup_res(). Note that this requires yfinance to be installed to fetch sample data.

    import trendln
    trendln.test_sup_res('.')
    pip install trendln --upgrade --no-cache-dir
  2. Calculate support and resistance with calc_support_resistance()

    master

    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))
  3. Plot support and resistance with dates using plot_sup_res_date()

    master

    plot_sup_res_date is a wrapper for plot_support_resistance that provides automatic date formatting for pandas date indexes (using a US trading calendar).

    Parameters:

    • hist: Input data (same as calc_support_resistance).
    • idx: The date index from a pandas DataFrame.
    • numbest, fromwindows, pctbound, extmethod, method, window, errpct, hough_scale, hough_prob_iter, sortError, accuracy: Same as calc_support_resistance and plot_support_resistance.

    Example:

    idx = hist[-1000:].index
    fig = trendln.plot_sup_res_date((hist[-1000:].Low, hist[-1000:].High), idx)
    plt.show()
    import trendln
    import matplotlib.pyplot as plt
    
    idx = hist[-1000:].index
    fig = trendln.plot_sup_res_date((hist[-1000:].Low, hist[-1000:].High), idx)
    plt.savefig('suppres.svg', format='svg')
    plt.show()
  4. Get local extrema with get_extrema()

    master

    Use get_extrema to find local minima and maxima indexes without performing the full trend line calculation. It accepts the same extmethod and accuracy parameters as calc_support_resistance.

    Returns:

    • A tuple (minimaIdxs, maximaIdxs).
    • If a 2-tuple (support, resistance) is provided where one is None, it returns only the requested side.

    Example:

    # Get both
    minimaIdxs, maximaIdxs = trendln.get_extrema(hist[-1000:].Close)
    
    # Get maxima only
    maximaIdxs = trendln.get_extrema((None, hist[-1000:].High))
    minimaIdxs, maximaIdxs = trendln.get_extrema(hist[-1000:].Close, extmethod=trendln.METHOD_NUMDIFF, accuracy=2)
  5. Plot support and resistance with plot_support_resistance()

    master

    The plot_support_resistance function calculates and plots the average and top numbest support and resistance lines, marking the extrema used. Requires matplotlib.

    Parameters:

    • hist: Input data (same as calc_support_resistance).
    • xformatter: X-axis data formatter (e.g., matplotlib.ticker.FuncFormatter).
    • numbest: Number of best support/resistance lines to display (default 2).
    • fromwindows: If True, draws numbest best from each window; otherwise draws numbest across the whole range.
    • pctbound: Bounds trend line based on this maximum percentage of the data range above high or below low.
    • extmethod, method, window, errpct, hough_prob_iter, sortError, accuracy: Same as calc_support_resistance.

    Returns:

    • The current matplotlib figure (matplotlib.pyplot.gcf()).
    import trendln
    import matplotlib.pyplot as plt
    
    fig = trendln.plot_support_resistance(hist[-1000:].Close)
    plt.savefig('suppres.svg', format='svg')
    plt.show()