Algorithmic Trading & Indicators
Intermediate
Calculate Linear Regression Channel, Slope & R-Squared Trend Strength in Python
Compute least-squares linear regression trendlines, upper/lower standard error channels, and R-squared trend linearity in Python Pandas.
#pandas#numpy#scipy
Problem Statement
Visual trendlines are subjective. Least-squares linear regression channels calculate objective slope, intercept, and R-squared goodness-of-fit to quantify trend linearity.
Formula / Core Logic
y = mx + c computed via scipy.stats.linregress over rolling N periods.
Installation
pip install pandas numpy scipy
linear-regression-channel-slope-momentum-python.py
import pandas as pd
import numpy as np
from scipy.stats import linregress
def linear_regression_channel(df, window=50, num_std=2.0):
df = df.copy()
slopes, intercepts, r_sqs, uppers, lowers = [], [], [], [], []
closes = df['Close'].values
for i in range(len(closes)):
if i < window:
slopes.append(np.nan); intercepts.append(np.nan); r_sqs.append(np.nan); uppers.append(np.nan); lowers.append(np.nan)
continue
y = closes[i - window + 1 : i + 1]
x = np.arange(window)
slope, intercept, r_val, p_val, std_err = linregress(x, y)
current_val = slope * (window - 1) + intercept
channel_width = std_err * window * num_std
slopes.append(slope); intercepts.append(intercept); r_sqs.append(r_val ** 2)
uppers.append(current_val + channel_width); lowers.append(current_val - channel_width)
df['Reg_Slope'] = slopes
df['Reg_R2'] = r_sqs
df['Reg_Upper'] = uppers
df['Reg_Lower'] = lowers
return df
Get the Complete 100+ Python Quant & Automation Bundle
Instant lifetime access to all production-ready scripts, valuation models, and trading bots ($19).
Buy Full Bundle on Gumroad ($19) →Frequently Asked Questions
Q: What does an R-squared value close to 1.0 signify?
An R-squared value above 0.85 indicates an exceptionally stable, linear trend channel with minimal noise.