Xem Tiếng Việt
Chương 18Original (EN)

Chapter 18: Automated Price Trend Lines in Python


Chapter Overview — 00:00

Trend lines are among the oldest and most universally applied tools in technical analysis. Discretionary traders use them to identify channels, ascending/descending triangles, wedges, and trend continuations. However, automating trend lines algorithmically has historically presented significant hurdles: standard linear regression cuts through the middle of price action rather than bounding it, while naive heuristic connections between random swing pivots often fail to capture the macro geometry.

This chapter details a constrained optimization algorithm designed to fit optimal upper (resistance) and lower (support) bounding trend lines to any price series.

                  OPTIMAL BOUNDING TREND LINES
       Price
         ▲        Upper Trendline (Resistance: bounding above, min SSE)
         │       /       ●─────────●
         │      /       /         /
         │     /       /         /
         │    /       /         /
         │   /       ●─────────●
         │  ● Pivot (Furthest below best fit line)
         │   \
         │    \ Lower Trendline (Support: bounding below, min SSE)
         └───────────────────────────────────────────────────► Time

Key features of this algorithm:

  • Single Hyperparameter: Requires only the window lookback length (NN candles).
  • Dual Formulations: Operates either purely on closing prices or on candle extremes (High/Low wicks).
  • Mathematical Rigor: Combines Ordinary Least Squares (OLS) baseline estimation with pivot anchoring and constrained gradient descent.
  • Dynamic Slope Indicator: Rolling calculations yield a continuous time-series indicator of trend-line slopes and channel convergence.

1. Algorithmic Principles & Geometry — 00:31

To fit a trend line that behaves like a human trader's drawing, the line must satisfy two criteria:

  1. Strict Bounding Constraint: A support line must lie below (or touch) every price point in the window; a resistance line must lie above (or touch) every price point.
  2. Proximity Minimization: Among all valid bounding lines, the chosen line must minimize the total distance (sum of squared errors) to the price action.

Three-Step Optimization Workflow

For a given window of prices P=[p0,p1,…,pN−1]P = [p_0, p_1, \dots, p_{N-1}]:

Step 1: Baseline OLS Fit

Fit a standard Ordinary Least Squares (OLS) regression line through the data: y^i=mols⋅i+bols\hat{y}_i = m_{\text{ols}} \cdot i + b_{\text{ols}} This baseline establishes the general drift and momentum of the price action.

Step 2: Pivot Point Identification

Calculate the vertical residual for each point: ri=pi−y^ir_i = p_i - \hat{y}_i.

  • Lower Trend Line Pivot (iloweri_{\text{lower}}): The point that drops furthest below the OLS line: ilower=arg⁡min⁡i(pi−y^i)i_{\text{lower}} = \arg\min_{i} (p_i - \hat{y}_i)
  • Upper Trend Line Pivot (iupperi_{\text{upper}}): The point that rises furthest above the OLS line: iupper=arg⁡max⁡i(pi−y^i)i_{\text{upper}} = \arg\max_{i} (p_i - \hat{y}_i)

By forcing the candidate trend line to pass through this extreme pivot point (xp,yp)(x_p, y_p), the line's intercept bb is uniquely determined by its slope mm: b=yp−m⋅xpb = y_p - m \cdot x_p

Step 3: Constrained Gradient Descent on Slope

With the pivot fixed, the line can only rotate around (xp,yp)(x_p, y_p). The algorithm performs gradient descent on the slope mm, starting from molsm_{\text{ols}}:

  • Objective Function: Minimize ∑i=0N−1(y^i(m)−pi)2\sum_{i=0}^{N-1} (\hat{y}_i(m) - p_i)^2.
  • Constraint Check:
    • For Support: y^i(m)≤pi+ϵ∀i\hat{y}_i(m) \le p_i + \epsilon \quad \forall i
    • For Resistance: y^i(m)≥pi−ϵ∀i\hat{y}_i(m) \ge p_i - \epsilon \quad \forall i
  • If a tested slope violates the constraint or increases squared error, the search step shrinks.

2. Python Implementation — 01:33

The algorithm consists of three modular functions: check_trendline, optimize_slope, and fit_trendline_single.

Step Verification Function

import numpy as np

def check_trendline(support: bool, pivot_idx: int, slope: float, data: np.ndarray, eps: float = 1e-5):
    """
    Evaluates candidate slope passing through pivot.
    Returns sum of squared errors if valid, or -1.0 if constraint is violated.
    """
    x = np.arange(len(data))
    pivot_val = data[pivot_idx]
    intercept = pivot_val - slope * pivot_idx
    line = slope * x + intercept
    
    diff = line - data
    
    if support:
        # Lower line must be below all data points (line <= data + eps)
        if np.any(diff > eps):
            return -1.0
        # Minimize distance from data to line
        return np.sum((data - line) ** 2)
    else:
        # Upper line must be above all data points (line >= data - eps)
        if np.any(diff < -eps):
            return -1.0
        # Minimize distance from line to data
        return np.sum((line - data) ** 2)

[!NOTE] Floating-Point Epsilon (ϵ\epsilon) Due to floating-point imprecision, checking line <= data directly can cause the pivot point itself (xpx_p) to register a false violation. Introducing an epsilon ϵ≈10−5\epsilon \approx 10^{-5} guarantees numerical stability.

Gradient Descent Optimization Loop — 02:50

The slope optimization uses numerical differentiation to guide slope adjustments:

def optimize_slope(support: bool, pivot_idx: int, initial_slope: float, data: np.ndarray):
    """
    Finds optimal bounding slope using adaptive step-size gradient descent.
    """
    slope = initial_slope
    # Scale initial step size based on data range and window length
    slope_unit = (np.max(data) - np.min(data)) / len(data)
    step = 1.0
    min_step = 1e-4
    h = 1e-5  # Finite difference delta
    
    current_loss = check_trendline(support, pivot_idx, slope, data)
    
    # If initial OLS slope is invalid, rotate until valid
    while current_loss < 0 and step > min_step:
        # Try both directions to find a valid starting boundary
        l_pos = check_trendline(support, pivot_idx, slope + step * slope_unit, data)
        l_neg = check_trendline(support, pivot_idx, slope - step * slope_unit, data)
        if l_pos >= 0:
            slope += step * slope_unit
            current_loss = l_pos
            break
        elif l_neg >= 0:
            slope -= step * slope_unit
            current_loss = l_neg
            break
        step *= 0.5

    while step > min_step:
        # Numerical derivative
        loss_plus = check_trendline(support, pivot_idx, slope + h, data)
        if loss_plus < 0 or current_loss < 0:
            step *= 0.5
            continue
            
        grad = (loss_plus - current_loss) / h
        direction = -1.0 if grad > 0 else 1.0
        
        new_slope = slope + direction * step * slope_unit
        new_loss = check_trendline(support, pivot_idx, new_slope, data)
        
        if new_loss >= 0 and new_loss < current_loss:
            slope = new_slope
            current_loss = new_loss
        else:
            step *= 0.5
            
    intercept = data[pivot_idx] - slope * pivot_idx
    return slope, intercept

High/Low vs. Close Fitting — 04:08

  • Close Only: Fits upper and lower lines using solely data = close.
  • High/Low Fit:
    1. Fit OLS baseline on close.
    2. Find upper pivot using high array: iupper=arg⁡max⁡(high−y^close)i_{\text{upper}} = \arg\max(high - \hat{y}_{\text{close}}).
    3. Find lower pivot using low array: ilower=arg⁡min⁡(low−y^close)i_{\text{lower}} = \arg\min(low - \hat{y}_{\text{close}}).
    4. Optimize upper slope against high array, and lower slope against low array.

3. Rolling Trend-Line Slope Indicator — 04:24

By applying this fitting routine across a sliding window (e.g., N=30N=30 days), traders can transform qualitative geometric lines into a quantitative time-series indicator:

  Slope
    ▲
 +m │           /── Upper Slope (Resistance)
    │          /
  0 ┼─────────/─────────────── Zero Line (Horizontal Trend)
    │        /
 -m │       /──── Lower Slope (Support)
    └──────────────────────────────────────► Time
            Wedge / Triangle Formation
            (Slopes converging toward 0)

Normalization with Log Prices

When computing trend lines over long historical horizons or high-growth assets (such as Bitcoin), raw dollar prices distort slopes: a 500moveat500 move at 3,000 is radically different from a 500moveat500 move at 60,000.

  • Solution: Always compute trend lines on logarithmic prices (ln⁡(Pt)\ln(P_t)).
  • A linear slope on log price represents a constant percentage rate of return per bar (m=Δln⁡P/Δtm = \Delta \ln P / \Delta t).

4. Strengths & Computational Trade-offs — 04:56

Advantages

  1. Mathematical Uniqueness: Eliminates subjective charting choices (which two wicks to connect). The result is fully deterministic and reproducible.
  2. True Bounding Support/Resistance: Unlike standard linear regression or moving average bands, lines never penetrate the price window during the lookback period.
  3. Parameter Parsimony: Only requires a single lookback parameter (NN), minimizing overfitting risk.

Computational Performance Bottleneck

Because the optimization loop performs iterative evaluations across all NN data points at each bar:

  • Daily Timeframes: Executes in acceptable time (seconds to low minutes for multi-year series).
  • Intraday Timeframes (1-Hour / 15-Minute): Pure Python execution becomes prohibitively slow across hundreds of thousands of candles.
  • Production Recommendation: For production backtesting or live deployment on high-frequency data, compile the inner loop using Numba (@njit) or re-implement in C++ / Rust / Cython.

Key Takeaways

  1. OLS Baseline + Pivot Anchoring Solves Dimensionality: Fixing the trendline intercept to the most extreme residual point reduces a 2D line search (m,b)(m, b) to a 1D bounded slope optimization (m)(m).
  2. Log Transforms are Mandatory: Always run price bounding algorithms on log prices to ensure slope comparability across differing volatility and price regimes.
  3. Slope Convergence Precedes Breakouts: Tracking the delta between upper and lower slope values provides a continuous metric for triangle consolidation and impending volatility expansion.

Nguồn duy nhất: Kênh YouTube chính thức của neurotrader. Nội dung được hệ thống hóa phục vụ học tập & tra cứu — bấm các mốc thời gian trong bài để xem trực tiếp video gốc của tác giả.