### Install trendln Source: https://github.com/gregorymorse/trendln/blob/master/README.md Installation commands for pip and conda. ```bash $ pip install trendln --upgrade --no-cache-dir ``` ```bash $ conda install -c GregoryMorse trendln ``` -------------------------------- ### Perform installation sanity check Source: https://github.com/gregorymorse/trendln/blob/master/README.md Verifies that the library is installed and methods are executing correctly. ```python 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 ``` -------------------------------- ### Plot support and resistance lines Source: https://github.com/gregorymorse/trendln/blob/master/README.md Calculates and plots support and resistance lines using matplotlib. Requires matplotlib to be installed. ```python 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 ``` ```python 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=2) # other parameters as per calc_support_resistance # fig - returns matplotlib.pyplot.gcf() or the current figure ``` -------------------------------- ### Calculate Support and Resistance with trendln Source: https://github.com/gregorymorse/trendln/blob/master/README.md Demonstrates basic usage of calc_support_resistance to identify support and resistance levels from financial data. ```python 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 ``` -------------------------------- ### Configure calc_support_resistance Parameters Source: https://github.com/gregorymorse/trendln/blob/master/README.md Detailed configuration options for the calc_support_resistance function, including method selection and error thresholds. ```python (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 exhaustive 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=4 accuracy=2) ``` -------------------------------- ### Configure Extrema Detection Methods Source: https://context7.com/gregorymorse/trendln/llms.txt Constants for configuring extrema detection algorithms, which can be passed as integers or string names. ```python import trendln # Extrema detection methods (extmethod parameter) # METHOD_NAIVE (0) - Local min/max for single interval, requires pandas # METHOD_NAIVECONSEC (1) - Handles consecutive equal values, requires pandas ``` -------------------------------- ### Calculate support and resistance levels Source: https://context7.com/gregorymorse/trendln/llms.txt Use calc_support_resistance to identify price levels using specified numerical differentiation and trend line calculation methods. ```python mins, maxs = trendln.calc_support_resistance( prices, extmethod='METHOD_NUMDIFF', # Same as trendln.METHOD_NUMDIFF method='METHOD_NSQUREDLOGN' # Same as trendln.METHOD_NSQUREDLOGN ) ``` -------------------------------- ### Generate learning figures Source: https://github.com/gregorymorse/trendln/blob/master/README.md Generates reference figures for learning purposes. ```python trendln.plot_sup_res_learn('.', hist) ``` ```python 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 ``` -------------------------------- ### Calculate Support and Resistance Trend Lines Source: https://context7.com/gregorymorse/trendln/llms.txt Calculates support and resistance lines from price data using various configurable methods. Supports single price series or separate low/high price inputs. ```python import trendln import numpy as np # Example with simulated price data prices = [100.0, 102.5, 101.0, 104.0, 103.5, 106.0, 104.5, 108.0, 107.0, 110.0, 108.5, 107.0, 109.0, 106.5, 108.0, 105.0, 107.5, 104.0, 106.0, 103.0] # Calculate support and resistance for a single price series mins, maxs = trendln.calc_support_resistance(prices) # Unpack results minimaIdxs, pmin, mintrend, minwindows = mins maximaIdxs, pmax, maxtrend, maxwindows = maxs print(f"Local minima at indices: {minimaIdxs}") print(f"Local maxima at indices: {maximaIdxs}") print(f"Average support line: slope={pmin[0]:.4f}, intercept={pmin[1]:.4f}") print(f"Average resistance line: slope={pmax[0]:.4f}, intercept={pmax[1]:.4f}") # Each trend line contains: (point_indices, (slope, intercept, SSR, slopeErr, interceptErr, areaAvg)) for i, (points, result) in enumerate(mintrend[:2]): slope, intercept, ssr, slope_err, int_err, area = result print(f"Support line {i+1}: points={points}, slope={slope:.4f}, intercept={intercept:.4f}") # Calculate support only using low prices (pass None for resistance) low_prices = [99.0, 101.5, 100.0, 103.0, 102.5, 105.0, 103.5, 107.0, 106.0, 109.0, 107.5, 106.0, 108.0, 105.5, 107.0, 104.0, 106.5, 103.0, 105.0, 102.0] support_result = trendln.calc_support_resistance((low_prices, None)) minimaIdxs, pmin, mintrend, minwindows = support_result # Calculate both with separate low/high series high_prices = [101.0, 103.5, 102.0, 105.0, 104.5, 107.0, 105.5, 109.0, 108.0, 111.0, 109.5, 108.0, 110.0, 107.5, 109.0, 106.0, 108.5, 105.0, 107.0, 104.0] mins, maxs = trendln.calc_support_resistance((low_prices, high_prices)) # Using different calculation methods # METHOD_NCUBED - exhaustive O(n^3) search, most accurate # METHOD_NSQUREDLOGN - O(n^2 log n) search, good balance (default) # METHOD_HOUGHPOINTS - Hough transform for points # METHOD_HOUGHLINES - image-based Hough transform (requires scikit-image) mins, maxs = trendln.calc_support_resistance( prices, method=trendln.METHOD_NSQUREDLOGN, extmethod=trendln.METHOD_NUMDIFF, window=125, # Window size for trend line search errpct=0.005, # Maximum slope standard error percentage accuracy=2, # Numerical differentiation accuracy (even integer) sortError=False # Sort by area (True) or slope error (False) ) ``` -------------------------------- ### Evaluate Support/Resistance Levels Source: https://context7.com/gregorymorse/trendln/llms.txt Computes support and resistance levels at a specific index using pre-calculated data. Useful for real-time trading decisions. Specify the index, current price, and max number of levels. ```python import trendln # First compute support/resistance prices = [100.0, 105.0, 98.0, 110.0, 102.0, 115.0, 108.0, 120.0, 112.0, 118.0, 106.0, 122.0, 110.0, 125.0, 115.0, 128.0, 118.0, 130.0, 120.0, 126.0] calc_result = trendln.calc_support_resistance(prices) # Get levels at the last bar current_index = len(prices) - 1 current_price = prices[-1] supports, resistances, rr_ratios = trendln.get_levels( calc_result, x=current_index, # Index to evaluate at price=current_price, # Current price for classification n=3 # Max number of levels to return ) # Each support/resistance entry: (level, strength, slope, intercept) print("Support levels (nearest first):") for level, strength, slope, intercept in supports: print(f" Level: {level:.2f}, Strength: {strength} touches, Slope: {slope:.4f}") print("\nResistance levels (nearest first):") for i, (level, strength, slope, intercept) in enumerate(resistances): rr = rr_ratios[i] rr_str = f"{rr:.2f}" if rr is not None and rr != float('inf') else str(rr) print(f" Level: {level:.2f}, Strength: {strength}, R:R ratio: {rr_str}") ``` -------------------------------- ### Plot Support and Resistance with Date Index Source: https://context7.com/gregorymorse/trendln/llms.txt Visualizes trend lines with x-axis date formatting. Useful for financial time series data. ```python import trendln import pandas as pd import matplotlib.pyplot as plt # Create sample data with date index dates = pd.date_range(start='2024-01-01', periods=30, freq='B') # Business days prices = [100.0, 105.0, 98.0, 110.0, 102.0, 115.0, 108.0, 120.0, 112.0, 118.0, 106.0, 122.0, 110.0, 125.0, 115.0, 128.0, 118.0, 130.0, 120.0, 126.0, 114.0, 132.0, 122.0, 135.0, 125.0, 138.0, 128.0, 140.0, 130.0, 136.0] # Plot with date formatting fig = trendln.plot_sup_res_date( prices, idx=dates, numbest=2, title='Stock Price Analysis - Q1 2024', y_axis_label='Price ($)', series_label='Close' ) plt.tight_layout() plt.savefig('dated_trendlines.png', dpi=150) plt.show() plt.clf() # With OHLC candlestick overlay opens = [100.0, 102.0, 99.0, 108.0, 103.0, 113.0, 109.0, 118.0, 113.0, 117.0, 107.0, 120.0, 111.0, 123.0, 116.0, 126.0, 119.0, 128.0, 121.0, 125.0, 115.0, 130.0, 123.0, 133.0, 126.0, 136.0, 129.0, 138.0, 131.0, 135.0] highs = [106.0, 108.0, 99.0, 112.0, 106.0, 117.0, 112.0, 122.0, 116.0, 120.0, 110.0, 124.0, 114.0, 127.0, 119.0, 130.0, 122.0, 132.0, 124.0, 128.0, 118.0, 134.0, 126.0, 137.0, 129.0, 140.0, 132.0, 142.0, 134.0, 138.0] lows = [99.0, 101.0, 97.0, 107.0, 101.0, 112.0, 107.0, 117.0, 111.0, 115.0, 105.0, 118.0, 109.0, 121.0, 114.0, 124.0, 117.0, 126.0, 119.0, 123.0, 113.0, 128.0, 121.0, 131.0, 124.0, 134.0, 127.0, 136.0, 129.0, 133.0] closes = prices fig = trendln.plot_sup_res_date( (lows, highs), idx=dates, numbest=2, title='OHLC Chart with Trend Lines', ohlc=(opens, highs, lows, closes), # Candlestick overlay show_average=False, extend_to_end=True ) plt.tight_layout() plt.savefig('candlestick_trendlines.png', dpi=150) plt.show() # Integration with yfinance # import yfinance as yf # ticker = yf.Ticker('AAPL') # hist = ticker.history(period='1y') # fig = trendln.plot_sup_res_date( # (hist.Low, hist.High), # hist.index, # numbest=3, # ohlc=(hist.Open, hist.High, hist.Low, hist.Close), # title='AAPL Support/Resistance Analysis' # ) # plt.show() ``` -------------------------------- ### Find Horizontal Support/Resistance Zones Source: https://context7.com/gregorymorse/trendln/llms.txt Identifies horizontal support and resistance zones by clustering pivot prices within a specified percentage tolerance. Requires minimum touches to define a level. ```python import trendln # Price data with horizontal support/resistance zones prices = [100.0, 105.0, 100.5, 108.0, 99.8, 112.0, 100.2, 115.0, 99.5, 118.0, 120.0, 115.5, 122.0, 119.8, 125.0, 120.2, 128.0, 119.5, 130.0, 120.0] support_levels, resistance_levels = trendln.get_horizontal_levels( prices, pctbound=0.05, # 5% tolerance for clustering prices min_touches=2, # Minimum pivot points to form a level accuracy=2 ) # Each level: (mean_price, touch_count, pivot_indices) print("Horizontal Support Zones:") for mean_price, touches, indices in support_levels: print(f" Price: {mean_price:.2f}, Touches: {touches}, At bars: {indices}") print("\nHorizontal Resistance Zones:") for mean_price, touches, indices in resistance_levels: print(f" Price: {mean_price:.2f}, Touches: {touches}, At bars: {indices}") # With separate low/high data low_prices = [99.0, 104.0, 99.5, 107.0, 98.8, 111.0, 99.2, 114.0, 98.5, 117.0] high_prices = [101.0, 106.0, 101.5, 109.0, 100.8, 113.0, 101.2, 116.0, 100.5, 119.0] support_levels, resistance_levels = trendln.get_horizontal_levels( (low_prices, high_prices), pctbound=0.03, min_touches=2 ) ``` -------------------------------- ### Detect Extrema with Numerical Differentiation Source: https://context7.com/gregorymorse/trendln/llms.txt Uses numerical differentiation to find local minima and maxima in price data. Set accuracy for differentiation and include_edge to consider endpoints. ```python minimaIdxs, maximaIdxs = trendln.get_extrema( prices, extmethod=trendln.METHOD_NUMDIFF, accuracy=2, # Differentiation accuracy (2, 4, 6, or 8) include_edge=True # Include first/last points as potential extrema ) ``` -------------------------------- ### Plot Support and Resistance Trend Lines Source: https://context7.com/gregorymorse/trendln/llms.txt Visualizes support and resistance lines on price data. Supports basic plots, customized configurations, separate low/high data, and embedding in matplotlib subplots. ```python import trendln import matplotlib.pyplot as plt # Sample price data prices = [100.0, 105.0, 98.0, 110.0, 102.0, 115.0, 108.0, 120.0, 112.0, 118.0, 106.0, 122.0, 110.0, 125.0, 115.0, 128.0, 118.0, 130.0, 120.0, 126.0, 114.0, 132.0, 122.0, 135.0, 125.0, 138.0, 128.0, 140.0, 130.0, 136.0] # Basic plot fig = trendln.plot_support_resistance(prices) plt.savefig('basic_trendlines.png', dpi=150) plt.show() plt.clf() # Customized plot fig = trendln.plot_support_resistance( prices, numbest=2, # Show top 2 support and resistance lines fromwindows=True, # Best from each window (vs. overall best) pctbound=0.1, # 10% bound for extending lines window=125, # Window size for analysis errpct=0.005, # Error percentage threshold sortError=False, # Sort by area under curve title='Stock Price with Support/Resistance', y_axis_label='Price ($)', series_label='Close', show_average=True, # Show average trend lines extend_to_end=True # Extend lines to last bar ) plt.tight_layout() plt.savefig('custom_trendlines.svg', format='svg') plt.clf() # Plot with separate low/high data low_prices = [99.0, 104.0, 97.0, 109.0, 101.0, 114.0, 107.0, 119.0, 111.0, 117.0] high_prices = [101.0, 106.0, 99.0, 111.0, 103.0, 116.0, 109.0, 121.0, 113.0, 119.0] fig = trendln.plot_support_resistance( (low_prices, high_prices), numbest=3, title='Price Range with Trend Lines' ) plt.show() # Embed in subplot fig, axes = plt.subplots(2, 1, figsize=(12, 8)) trendln.plot_support_resistance(prices, ax=axes[0], title='First Stock') trendln.plot_support_resistance(low_prices, ax=axes[1], title='Second Stock') plt.tight_layout() plt.savefig('multi_chart.png', dpi=150) ``` -------------------------------- ### calc_support_resistance Source: https://github.com/gregorymorse/trendln/blob/master/README.md Calculates support and resistance information including local extrema, average, and trend lines for a given time series. ```APIDOC ## calc_support_resistance ### Description Calculates support and resistance trend lines for time series data using various detection and regression methods. ### Parameters #### Arguments - **h** (list/ndarray/Series/tuple) - Required - Data as a 1D array or a 2-tuple (support, resistance) where one can be None. - **extmethod** (enum) - Optional - Method for finding local extrema (METHOD_NAIVE, METHOD_NAIVECONSEC, METHOD_NUMDIFF). - **method** (enum) - Optional - Method for calculating trend lines (METHOD_NCUBED, METHOD_NSQUREDLOGN, METHOD_HOUGHPOINTS, METHOD_HOUGHLINES, METHOD_PROBHOUGH). - **window** (int) - Optional - Window size for searching trend lines. - **errpct** (float) - Optional - Maximum percentage slope standard error. - **hough_scale** (float) - Optional - Smallest unit increment for Hough methods. - **hough_prob_iter** (int) - Optional - Number of iterations for METHOD_PROBHOUGH. - **sortError** (bool) - Optional - Sort by area under wrong side of curve if True, else by slope standard error. - **accuracy** (int) - Optional - Accuracy parameter for METHOD_NUMDIFF. ### Response #### Success Response - **minimaIdxs** (list) - Sorted list of indexes to local minima. - **pmin** (list) - [slope, intercept] of average best fit line through local minima. - **mintrend** (list) - Sorted list containing (points, result) for local minima trend lines. - **maximaIdxs** (list) - Sorted list of indexes to local maxima. - **pmax** (list) - [slope, intercept] of average best fit line through local maxima. - **maxtrend** (list) - Sorted list containing (points, result) for local maxima trend lines. ``` -------------------------------- ### Plot support and resistance with date formatting Source: https://github.com/gregorymorse/trendln/blob/master/README.md Plots support and resistance lines specifically for pandas date-indexed data. ```python 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 ``` ```python 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=2) # other parameters as per plot_support_resistance ``` -------------------------------- ### Calculate local extrema with trendln Source: https://github.com/gregorymorse/trendln/blob/master/README.md Calculates local minima and maxima from historical data. Supports passing single series or tuples of (low, high) data. ```python 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)) ``` ```python minimaIdxs, maximaIdxs = trendln.get_extrema( h, extmethod=METHOD_NUMDIFF, accuracy=2) # parameters and results are as per defined for calc_support_resistance ``` -------------------------------- ### get_horizontal_levels Source: https://context7.com/gregorymorse/trendln/llms.txt Finds horizontal support and resistance zones by clustering pivot prices. ```APIDOC ## get_horizontal_levels ### Description Identifies flat support and resistance zones by clustering pivot prices within a specified percentage tolerance. ### Parameters #### Query Parameters - **prices** (list/tuple) - Required - Price data or (low, high) tuple. - **pctbound** (float) - Optional - Percentage tolerance for clustering. - **min_touches** (int) - Optional - Minimum pivot points to form a level. - **accuracy** (int) - Optional - Accuracy parameter. ### Response - **support_levels** (list) - List of (mean_price, touch_count, pivot_indices). - **resistance_levels** (list) - List of (mean_price, touch_count, pivot_indices). ``` -------------------------------- ### Detect Local Extrema Source: https://context7.com/gregorymorse/trendln/llms.txt Identifies local minima and maxima (pivot points) in price data without performing full trend line calculations. ```python import trendln # Sample price data prices = [100.0, 102.0, 99.0, 104.0, 101.0, 106.0, 103.0, 108.0, 105.0, 110.0] # Get both minima and maxima indices minimaIdxs, maximaIdxs = trendln.get_extrema(prices) print(f"Minima at indices: {minimaIdxs}") # Local lows print(f"Maxima at indices: {maximaIdxs}") # Local highs # Get only maxima using high prices high_prices = [101.0, 103.0, 100.0, 105.0, 102.0, 107.0, 104.0, 109.0, 106.0, 111.0] maximaIdxs = trendln.get_extrema((None, high_prices)) print(f"Maxima only: {maximaIdxs}") # Get only minima using low prices low_prices = [99.0, 101.0, 98.0, 103.0, 100.0, 105.0, 102.0, 107.0, 104.0, 109.0] minimaIdxs = trendln.get_extrema((low_prices, None)) print(f"Minima only: {minimaIdxs}") ``` -------------------------------- ### get_levels Source: https://context7.com/gregorymorse/trendln/llms.txt Evaluates computed trend lines at a specific index to find current support and resistance levels. ```APIDOC ## get_levels ### Description Evaluates pre-computed trend lines at a specific index to identify support and resistance levels, their strength, and risk-to-reward ratios. ### Parameters #### Query Parameters - **calc_result** (object) - Required - Result from calc_support_resistance. - **x** (int) - Required - Index to evaluate at. - **price** (float) - Required - Current price for classification. - **n** (int) - Optional - Max number of levels to return. ### Response - **supports** (list) - List of (level, strength, slope, intercept) tuples. - **resistances** (list) - List of (level, strength, slope, intercept) tuples. - **rr_ratios** (list) - List of risk-to-reward ratios. ``` -------------------------------- ### get_extrema Source: https://context7.com/gregorymorse/trendln/llms.txt Detects local minima and maxima in a price series using various differentiation methods. ```APIDOC ## get_extrema ### Description Detects local minima and maxima in a price series. Supports multiple detection methods including naive, consecutive-handling, and numerical differentiation. ### Parameters #### Query Parameters - **prices** (list) - Required - List of price values. - **extmethod** (constant) - Optional - Detection method (METHOD_NAIVE, METHOD_NAIVECONSEC, METHOD_NUMDIFF). - **accuracy** (int) - Optional - Differentiation accuracy (2, 4, 6, or 8). - **include_edge** (bool) - Optional - Whether to include first/last points as potential extrema. ### Response - **minimaIdxs** (list) - Indices of detected minima. - **maximaIdxs** (list) - Indices of detected maxima. ``` -------------------------------- ### get_extrema Source: https://context7.com/gregorymorse/trendln/llms.txt Detects local minima and maxima (pivot points) in price data without performing full trend line calculations. ```APIDOC ## get_extrema ### Description Detects local minima and maxima (pivot points) in price data without performing full trend line calculations. Useful when you only need to identify turning points in the data. ### Parameters #### Request Body - **prices** (list or tuple) - Required - Single price series or a tuple of (low_prices, high_prices). ### Response - **minimaIdxs** (list) - Indices of local minima. - **maximaIdxs** (list) - Indices of local maxima. ``` -------------------------------- ### pandas_to_ohlc Source: https://context7.com/gregorymorse/trendln/llms.txt Converts pandas DataFrames to the tuple format required by trendln. ```APIDOC ## pandas_to_ohlc ### Description Converts a pandas DataFrame containing OHLC data into a tuple format (Low series, High series) expected by other trendln functions. ### Parameters #### Query Parameters - **df** (DataFrame) - Required - Pandas DataFrame with price data. - **low_col** (str) - Optional - Override for low column name. - **high_col** (str) - Optional - Override for high column name. - **close_col** (str) - Optional - Override for close column name. ### Response - **ohlc** (tuple) - Tuple containing Low and High series. ``` -------------------------------- ### Convert Pandas DataFrame to OHLC Tuple Source: https://context7.com/gregorymorse/trendln/llms.txt Converts pandas DataFrames with OHLC columns into the tuple format required by trendln functions. Supports auto-detection of standard column names or explicit column overrides. ```python import trendln import pandas as pd # Create sample OHLC DataFrame (similar to yfinance output) data = { 'Open': [100.0, 102.0, 101.0, 104.0, 103.0], 'High': [103.0, 105.0, 104.0, 107.0, 106.0], 'Low': [99.0, 101.0, 100.0, 103.0, 102.0], 'Close': [102.0, 104.0, 103.0, 106.0, 105.0], 'Volume': [1000, 1200, 1100, 1300, 1250] } df = pd.DataFrame(data) # Auto-detect Low and High columns ohlc = trendln.pandas_to_ohlc(df) # Returns (Low series, High series) # Use with calc_support_resistance mins, maxs = trendln.calc_support_resistance(ohlc) # With explicit column names (for non-standard DataFrames) custom_df = pd.DataFrame({ 'price_low': [99.0, 101.0, 100.0], 'price_high': [103.0, 105.0, 104.0], 'price_close': [102.0, 104.0, 103.0] }) ohlc = trendln.pandas_to_ohlc( custom_df, low_col='price_low', high_col='price_high' ) # Close-only analysis close_only = trendln.pandas_to_ohlc(df, close_col='Close') mins, maxs = trendln.calc_support_resistance(close_only) # Integration with yfinance # import yfinance as yf # ticker = yf.Ticker('^GSPC') # hist = ticker.history(period='1y') # ohlc = trendln.pandas_to_ohlc(hist) # mins, maxs = trendln.calc_support_resistance(ohlc) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.