We have all seen and tried drawing some trendlines on the charts. Wedges, channels, support, resistance, you name it. But how do we draw them algorithmically? I will demonstrate here using Python software.
I have came upon an interesting way to draw them, that is also relatively computationally fast, even without any optimization.
First, let’s find the best fit line using least squares method.

Least Squares method simply finds a line between the points that minimizes the distance between the line and all points. Simple as that! Numpy has a function that does it all for us:
X = np.arange(len(close))
# coefs[0] = slope; coefs[1] = intercept
coefs = np.polyfit(X, close, 1)
# Formula: y=mx+c
Afterwards, we find a maximum and minimum points.

We can find them simply using argmax() and argmin() functions, that return their index number.
upper_pivot = (high - line_points).argmax()
lower_pivot = (low - line_points).argmin()
Next step: Draw the line.

Final Step: Optimize the line.

Rules for optimization:
1) Line cannot go beyond any point
2) Line must be as close to the best-fit line as possible
Once done, we can begin charting. The results are shown below:
Using Close price

Using High/Low prices & also extended by a few bars

Leave a Reply