We collect cookies to improve your browsing experience. By using our site, you agree to ourPrivacy Policy andTerms of Service.

Drawing a trend line by hand is easy enough. Deciding which highs or lows deserve to anchor it is where the arguments start. A dynamic fitted channel gives us a repeatable way to describe the direction of a market, pick out where price is at a relevant extreme versus its average, and spot trend changes in real time.
This week we’re using QQQ to build those channels in Python. We’ll start with a line of best fit, look at two ways to place upper and lower boundaries around it, then move the calculation through time and observe the change. This methodology allows us to choose the timeframe and let the same calculation construct our trendlines.
For the tutorial today we are using daily OHLC prices up to 3 November 2026. Our main example covers two years' data and is a good trading chart, but we’ll also include five and nine year charts, and then to show the method works equally as well on lower time horizons we will include the latest 30 days.
The examples assume our prices are already in a pandas DataFrame called df, sorted from oldest to newest, with one row per session and the columns Date, Open, High, Low and Close. Date is a datetime column and the price columns contain numeric values without gaps. We’ll use NumPy for the calculation and Plotly for the charts.
import pandas as pdimport numpy as npimport plotly.graph_objects as go
Finding our line of best fit
This code calculates a linear regression line through the midpoint of each candlestick’s high and low prices. The result is a straight line that represents the overall direction of price movement across the selected dataset. Unlike a moving average, which continuously adapts to recent prices, linear regression finds the single straight line that best fits all the observations.
First, a copy of the original DataFrame is created, and np.arange() generates a numerical sequence representing each candlestick’s position in time. The midpoint price is then calculated as (High + Low) / 2, providing a central value for each candle rather than relying solely on its closing price. These midpoint prices are converted into a NumPy array and passed to np.polyfit(), which calculates the straight line that best fits the data using the least squares method, minimising the sum of squared differences between the observed prices and the fitted line.
df1 = df.copy()x = np.arange(len(df1))
mid_price = ((df1["High"] + df1["Low"]) / 2).to_numpy()m, b = np.polyfit(x, mid_price, 1)df1['midline'] = m * x + b
The regression line follows the equation y = mx + b, where m represents the slope (the average change in price per candlestick) and b represents the intercept (the estimated price when x = 0). A positive slope indicates an upward trend, while a negative slope indicates a downward trend. The final calculation, m * x + b, generates the fitted price for every candlestick and stores these values in the midline column. The result is a straight line representing the overall price trend across the selected dataset, smoothing out short-term fluctuations to highlight the underlying direction of the market.
What the residuals tell us
A residual is the difference between an observed value and the value predicted by the regression line. If a session’s midpoint is above the line of best fit, its residual is positive. If it is below, the residual is negative. In the illustration below, the dotted vertical segments are the residuals, and show us the spread between the red dots (price) and the white regression line.

We can use the standard deviation of those residuals to set the distance from the middle line to each boundary. More scatter around the trend produces a wider channel; a closer fit produces a narrower one. The first example uses one residual standard deviation on each side.
n = 1residual = mid_price - df1['midline']deviation = np.nanstd(residual)df1['upper'] = df1['midline'] + n * deviationdf1['lower'] = df1['midline']- n * deviation
Here, residual contains the signed differences between each candlestick’s midpoint and the regression line, while deviation measures their spread. Adding and subtracting the same distance creates upper and lower boundaries that run parallel to the fitted line. Crucially, because these boundaries are calculated from the residuals, the channel automatically adapts to the relative price extremes observed in the historical OHLC data.
Periods of greater price dispersion produce wider channels, while periods where prices remain closely aligned with the underlying trend produce narrower ones. This allows the channel to reflect the characteristic price fluctuations of the instrument and period being analysed, rather than relying on arbitrary fixed distances. Increasing n widens the channel without changing its slope. These boundaries describe historical price dispersion, rather than guaranteeing that future prices will remain within them.
A second way to set width
An alternative approach is to calculate the standard deviation of the fitted midline values themselves, rather than the residuals. Although both methods use standard deviation, they measure fundamentally different characteristics of price movement. Residual standard deviation measures how far prices fluctuate around the regression line, while midline standard deviation measures how much the fitted trend changes over the period. A steeper trend or longer observation window will generally produce wider boundaries using this second method.
std = df1['midline'].std()df1['upper1'] = df1['midline'] + n * stddf1['lower1'] = df1['midline'] - n * std
This distinction is important because midline dispersion is driven by the strength of the fitted price movement, rather than the fluctuations around it. Consider a market moving sharply sideways: its regression line might be almost flat, producing very narrow boundaries despite substantial price volatility. Conversely, a market following a strong, consistent upward trend could produce wide boundaries even when prices remain closely aligned with the regression line.
In our two-year QQQ example, the standard deviation of the residuals is $31.47, compared with $79.15 for the fitted midline. Both calculations use the same underlying OHLC data and regression line, but produce considerably different results. In the chart below, the dotted grey boundaries represent residual dispersion, while the red boundaries represent midline dispersion.

Neither method is inherently incorrect; they simply answer different questions. Residual-based channels describe how far prices typically deviate from their underlying trend, making them more suitable for identifying relative price extremes. Midline-based channels instead reflect the magnitude of the fitted trend’s movement over the observation period, providing a different perspective on the market’s directional behaviour.
When constructing our regression channel using residuals, we found that setting n = 1 produced boundaries that were consistently too narrow to adequately capture the wider price movements observed in the OHLC data. To address this, we increased the standard deviation multiplier to n = 2, placing the upper and lower boundaries two residual standard deviations away from the fitted midline.
This effectively doubles the width of the channel, allowing it to accommodate a greater range of price fluctuations while remaining responsive to the underlying price dispersion. The result is a channel that better reflects the relative price extremes observed over the selected period, without altering the slope or position of the regression line, as you will see from the charts we construct below.
Adding trend channels to a chart
Once the columns are ready, we set Date as the index and using the Plotly library we draw our candlesticks, saving our chart data and settings into a variable called 'fig'. We then add the fitted midline, using the Plotly 'add_trace' method.
df1.set_index('Date', inplace=True)
fig = go.Figure(data=[go.Candlestick(x=df1.index, open=df1['Open'], high=df1['High'], low=df1['Low'], close=df1['Close'], increasing_line_color = 'rgba(19,156,19,0.8)', decreasing_line_color = 'rgba(175,07,49,0.8)', name = 'QQQ')])
fig.add_trace(go.Scatter(x=df1.index, y=df1.midline, opacity=0.8, line=dict(color='white', width=0.7), name='MIDLINE'))
To create white boundaries in the charts below, we add the data in our upper and lower columns to fig, these being our upper and lower channel boundaries calculated from residuals. We then set our theme to dark, update the grid colour, and create a rangebreak for weekend days where there is no price data to display (removes gaps).
fig.add_trace(go.Scatter(x=df1.index, y=df1.upper, opacity=0.8, line=dict(color='white', width=1), name='RES_UPPER'))
fig.add_trace(go.Scatter(x=df1.index, y=df1.lower, opacity=0.8, line=dict(color='white', width=1), name='res_LOWER'))
fig.update_layout(autosize=False, width=1000, height=600, xaxis_rangeslider_visible=False, template="plotly_dark") fig.update_yaxes(gridcolor="#171717") fig.update_xaxes(gridcolor="#171717")
fig.update_xaxes( rangebreaks=[ dict(bounds=["sat", "mon"]), ])
fig.show()
How Dynamic Trend Channels Adapt to Different Timeframes
One of the advantages of regression-based trend channels is their ability to adapt to different timeframes without changing the underlying calculation. By adjusting the number of observations used in the regression, we can examine both long term market trends and shorter term price movements using exactly the same methodology.
For the following examples, we use QQQ (Nasdaq-100 ETF) and maintain a residual standard deviation multiplier of n = 2 throughout. This places the upper and lower boundaries two standard deviations away from the fitted midline. As we change the observation period, the regression recalculates its slope and intercept, while the residual standard deviation adjusts the channel width to reflect the dispersion of prices around the new trend.
Nine Year Trend Channel
Our first example uses approximately nine years of daily OHLC data, providing a broad perspective on QQQ’s long-term price development. Despite several significant market corrections, including the declines of 2018, 2020 and 2022, the regression line slopes steadily upwards, but note that the recent moves above the upper boundary have brought sharp pullbacks each time.

Five Year Trend Channel
The five year regression continues to indicate a positive underlying trend, but its fitted values differ from the nine-year calculation because earlier price observations have been excluded. Notably, the 2025 market decline reversed sharply once outside the lower trend channel, and the most recent moves lower were from the upper line, reversing at the midline each time.

Two Year Trend Channel
Narrowing the time window further, the two year regression maintains an upward slope, but price has been at relative extremes more often. The sharp corrections during 2025 and 2026 that moved price below the lower boundary, and the more recent peak above the upper channel, all produced sharp, tradable reversals. We like this timeframe (or shorter) for swing trading.

30 Day Trend Channel
The latest 30 day trend channel slopes downwards, while the major trend is still up, and emphasises why the chosen trading time horizon matters. While the methodology works well, it tells us we should keep the horizon tied to the question we’re asking, rather than keep changing it until the picture supports a preferred view.

Watching the channels dynamically adjust to price
So far, we’ve calculated regression channels using fixed periods of historical data. However, financial markets are constantly evolving, and a trend that accurately describes price movements today may look very different several weeks from now. To demonstrate how our regression channels adapt as new information becomes available, our final example introduces a rolling regression window, allowing us to recalculate the trend and its boundaries as we move through the dataset.
Setting Up the Rolling Window
The code begins by defining a rolling window of 86 trading sessions, an animation speed of 80 milliseconds per frame, and a standard deviation multiplier of n = 2. The for loop then moves through the dataset one session at a time, selecting the most recent 86 observations using .iloc[]. For each window, we calculate the midpoint of every candlestick using its high and low prices, before applying np.polyfit() to determine the slope and intercept of the best-fitting regression line. As the window advances, the oldest observation is removed and a new one is added, allowing the regression line to continuously adjust its slope and position in response to changing market conditions.
Next, we calculate the residuals, representing the differences between the observed midpoint prices and their fitted values. The standard deviation of these residuals determines the distance between the regression midline and its upper and lower boundaries. With n = 2, these boundaries are positioned two residual standard deviations away from the midline, allowing the channel to widen or narrow as price dispersion changes. We also calculate the standard deviation of the fitted midline itself (std) to construct our alternative channel boundaries (up_line and dn_line) for comparison. The resulting calculations are repeated for every 86-session window, providing the foundation for our animation of how regression trend channels evolve over time.
window = 86 frame_rate = 80 n = 2
frames = [] for i in range(window-1, len(df1)): w = df1.iloc[i - window + 1 : i + 1]
x = np.arange(window) mid_price = ((w['High'] + w['Low'])/2).to_numpy() m, b = np.polyfit(x, mid_price, 1) midline = m*x + b
residuals = mid_price - midline deviation = np.nanstd(residuals) std = np.nanstd(midline)
up_res = midline + n * deviation dn_res = midline - n * deviation up_line = midline + std dn_line = midline - std
Creating the Animation Frames
Keep the next two code snippets inside the same for loop, directly after dn_line = midline - std.
Before generating each frame, we calculate the minimum and maximum values needed for the chart’s vertical axis. The y_min and y_max variables identify the lowest and highest values across the candlestick prices and both sets of channel boundaries. We then introduce a small padding of 3% to prevent the chart from appearing cramped. The resulting yrange ensures that the price action and regression channels remain visible as the animation progresses. Finally, last_label extracts the date of the most recent observation in the window, providing a unique identifier for each frame.
y_min = float(min(w['Low'].min(), dn_res.min(), dn_line.min())) y_max = float(max(w['High'].max(), up_res.max(), up_line.max())) pad = (y_max - y_min) * 0.03 if y_max > y_min else 1.0 yrange = [y_min - pad, y_max + pad]
last_label = (w.index[-1].date().isoformat() if isinstance(w.index, pd.DatetimeIndex) else str(w.index[-1]))
Next, we use Plotly’s go.Frame() to create an individual chart for each 86-session window. Each frame contains a candlestick chart displaying the OHLC data, a white regression midline, and two grey lines representing the upper and lower residual-based boundaries. These are created using go.Candlestick() and go.Scatter(), with the latter drawing the regression lines across the selected observations. The alternative standard deviation boundaries are included in the code but commented out, allowing us to enable them for comparison if required. Each completed frame is appended to the frames list, building the sequence of charts that will form our animation.
frames.append(go.Frame( name=last_label, data=[ go.Candlestick( x=w.index, open=w['Open'], high=w['High'], low=w['Low'], close=w['Close'], increasing_line_color='rgba(19,156,19,0.8)', decreasing_line_color='rgba(175,7,49,0.8)', showlegend=False, name='Price' ), go.Scatter( x=w.index, y=midline, mode="lines", line=dict(color='white', width=0.8), name="MIDLINE" ), go.Scatter( x=w.index, y=up_res, mode="lines", line=dict(color='gray', width=1), name="RES_UPPER" ), go.Scatter( x=w.index, y=dn_res, mode="lines", line=dict(color='gray', width=1), name="RES_LOWER" ), # go.Scatter(x=w.index, y=up_line, mode="lines", # line=dict(color='red', width=1), name="STD_UPPER"), # go.Scatter(x=w.index, y=dn_line, mode="lines", # line=dict(color='red', width=1), name="STD_LOWER"), ], layout=go.Layout( xaxis=dict(range=[w.index[0], w.index[-1]]), yaxis=dict(range=yrange) ) ))
Building the Interactive Animation
With our individual frames created, we can combine them into an interactive chart using Plotly’s go.Figure(). The data=frames[0].data argument displays the first frame when the chart initially loads, while frames=frames provides the complete sequence for the animation. We then configure the chart’s appearance using a dark theme, fixed dimensions and customised gridlines. The rangebreaks setting removes weekends from the horizontal axis, providing a continuous representation of trading sessions, while autorange=False allows each frame to control its own vertical axis range.
GREEN = "#00DF9A"
fig_anim = go.Figure( data=frames[0].data, frames=frames, layout=go.Layout( title="Rolling 86 Day Regression Channel", template="plotly_dark", width=1000, height=660, xaxis=dict( rangeslider=dict(visible=False), rangebreaks=[dict(bounds=["sat","mon"])], gridcolor="#171717" ), yaxis=dict(autorange=False, gridcolor="#171717"),
Finally, we add the interactive controls using Plotly’s updatemenus and sliders components. The Play button advances through the frames automatically at our chosen speed of 80 milliseconds per frame, while Pause stops the animation at its current position. The slider provides an alternative way to navigate through the dataset, allowing us to select individual trading sessions and examine their corresponding regression channels. Each slider position is linked to a frame using its date label, ensuring the displayed chart matches the selected observation. Once configured, fig_anim.show() renders the completed animation, demonstrating how the regression midline and its boundaries dynamically adjust as new price observations enter the rolling window.
updatemenus=[dict( type="buttons", direction="right", x=0.02, y=1.08, xanchor="left", yanchor="top", pad={"r": 10, "t": 0}, showactive=True, bgcolor=GREEN, bordercolor=GREEN, borderwidth=0, font=dict(color="black", size=12), buttons=[ dict(label="Play", method="animate", args=[None, {"frame":{"duration":frame_rate,"redraw":True}, "fromcurrent":True, "transition":{"duration":0}, "mode":"immediate"}]), dict(label="Pause", method="animate", args=[[None], {"mode":"immediate", "frame":{"duration":0,"redraw":False}, "transition":{"duration":0}}]), ], )],
sliders=[dict( y=-0.08, pad={"t": 30, "b": 0}, currentvalue={ "prefix": "Date: ", "offset": 20, "font": {"size": 12} }, steps=[dict( method="animate", args=[[f.name], {"mode":"immediate", "frame":{"duration":0,"redraw":True}, "transition":{"duration":0}}], label=f.name) for f in frames], )] ))
fig_anim.show()
Our final animation demonstrates how regression trend channels dynamically adapt as new price data becomes available, continuously adjusting their direction and width to reflect changing market conditions. By combining linear regression with residual standard deviation, we can construct a flexible framework for identifying underlying trends and relative price extremes across different timeframes.

You can download the complete Jupyter Notebook for free, including all the Python code covered in this tutorial, from our github account (link on the website). If you have any questions, please get in touch!

01-Dec-2026

30-Nov-2026

21-Nov-2026

14-Nov-2026

07-Nov-2026

02-Nov-2026

01-Nov-2026

28-Oct-2026

24-Oct-2026

17-Oct-2026

14-Oct-2026

10-Oct-2026

07-Oct-2026

03-Oct-2026

01-Oct-2026

30-Sept-2026

01-Sept-2026

21-Jun-2026

21-Jun-2026

14-Jun-2026

08-Jun-2026

01-Jun-2026

24-May-2026

17-May-2026

10-May-2026

03-May-2026

26-Apr-2026