pinescript, i was calculating linear regression and standard deviation manually to get slope and intercept for given range, however it seemed that some of calculated trendlines appear to be drawn "in reverse", for example for 5 consecutive falling bars i was getting rising trendline, to verify i've used built in ta.linreg indicator and i'm getting the same results (errors?)
is there any feature of linear regression which could cause such behaviour?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The behavior you're seeing with linear regression lines appearing "reversed" (showing rising trendlines for falling bars) is actually a normal characteristic of linear regression in certain situations, not an error. This can happen for several legitimate mathematical reasons:
Local vs Global Fitting: Linear regression finds the best fit line for ALL data points in your specified range, not just the most recent movement. If you have 5 consecutive falling bars but they're all still above the best-fit line that minimizes overall error across your entire lookback period, you'll get a rising trendline.
Endpoint Sensitivity: Linear regression is extremely sensitive to the endpoints of your data, especially with small sample sizes. With just 5 bars, the position of the first and last points has outsized influence on the slope.
Point Distribution: The way points are distributed can affect the regression line significantly. If most data points cluster in one region with a few outliers elsewhere, those outliers can dramatically pull the regression line.
Here's a simple example that demonstrates this counterintuitive behavior:
pinescript
//@version=5
indicator("LinReg Demo", overlay=true)
// Sample price series with 5 falling bars
price_series = close
// Calculate and plot linear regression line
linreg_val = ta.linreg(price_series, 20)
plot(linreg_val, color=color.red, linewidth=2, title="Linear Regression")
// Highlight last 5 bars for comparison
bgcolor(barstate.islast or barstate.islast[1] or barstate.islast[2] or barstate.islast[3] or barstate.islast[4] ? color.new(color.yellow, 90) : na)
To verify whether your implementation is correct, try these approaches:
Increase sample size: Use a larger number of bars (20+ instead of 5) for more stable results
Compare with built-in functions: If your manual calculations match ta.linreg, they're likely correct
Visualize all points: Plot all the points being used in your calculation to see why the line is behaving as it does
This is a normal characteristic of linear regression rather than a bug in either your calculation or the built-in functions. The regression is finding the mathematically optimal line to minimize squared error across ALL data points, which sometimes means the line appears counterintuitive when looking at just the most recent price action.