Chapter 18: Automated Price Trend Lines in Python
- Source: Automated Price Trend Lines in Python | Algorithmic Trading Indicator
- Channel: NeuroTrader
- Duration: 5:51
- Language: English
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 ( 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:
- 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.
- 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 :
Step 1: Baseline OLS Fit
Fit a standard Ordinary Least Squares (OLS) regression line through the data: This baseline establishes the general drift and momentum of the price action.
Step 2: Pivot Point Identification
Calculate the vertical residual for each point: .
- Lower Trend Line Pivot (): The point that drops furthest below the OLS line:
- Upper Trend Line Pivot (): The point that rises furthest above the OLS line:
By forcing the candidate trend line to pass through this extreme pivot point , the line's intercept is uniquely determined by its slope :
Step 3: Constrained Gradient Descent on Slope
With the pivot fixed, the line can only rotate around . The algorithm performs gradient descent on the slope , starting from :
- Objective Function: Minimize .
- Constraint Check:
- For Support:
- For Resistance:
- 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 () Due to floating-point imprecision, checking
line <= datadirectly can cause the pivot point itself () to register a false violation. Introducing an epsilon 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:
- Fit OLS baseline on
close. - Find upper pivot using
higharray: . - Find lower pivot using
lowarray: . - Optimize upper slope against
higharray, and lower slope againstlowarray.
- Fit OLS baseline on
3. Rolling Trend-Line Slope Indicator — 04:24
By applying this fitting routine across a sliding window (e.g., 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 3,000 is radically different from a 60,000.
- Solution: Always compute trend lines on logarithmic prices ().
- A linear slope on log price represents a constant percentage rate of return per bar ().
4. Strengths & Computational Trade-offs — 04:56
Advantages
- Mathematical Uniqueness: Eliminates subjective charting choices (which two wicks to connect). The result is fully deterministic and reproducible.
- True Bounding Support/Resistance: Unlike standard linear regression or moving average bands, lines never penetrate the price window during the lookback period.
- Parameter Parsimony: Only requires a single lookback parameter (), minimizing overfitting risk.
Computational Performance Bottleneck
Because the optimization loop performs iterative evaluations across all 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
- OLS Baseline + Pivot Anchoring Solves Dimensionality: Fixing the trendline intercept to the most extreme residual point reduces a 2D line search to a 1D bounded slope optimization .
- Log Transforms are Mandatory: Always run price bounding algorithms on log prices to ensure slope comparability across differing volatility and price regimes.
- Slope Convergence Precedes Breakouts: Tracking the delta between upper and lower slope values provides a continuous metric for triangle consolidation and impending volatility expansion.