Defining line_mse on "Identifying support and resistance blog"

I'm trying to replicate the results of "identifying support and resistance " blog on my local machine , but it keeps on giving, name error sayiing "line_mse is not defined"

Hi Mphahlela!



To fix this, you can first run the following code snippet:

# The line_mse() function computes and returns the mean squared error for
# the distance of all points from the line passing through points pt1 and pt2.

norm = np.linalg.norm

# Function takes two points pt1, pt2 and the minima/maxima dataset as input.
def line_mse(pt1, pt2, data):
    dist = 0
    dist_sq = 0
    sum_dist_sq = 0
    mean_sq_err = 0
    length = len(data)

    for pt3 in range(0, length):
            p1 = data[pt1]
            p2 = data[pt2]
            p3 = data[pt3]           
            
            # To calculate perpendicular distance of a point from line passing through pt1 and pt2
            dist = np.abs(norm(np.cross(p2-p1, p1-p3)))/norm(p2-p1)            
            # Squared error of a point from line passing through pt1 and pt2
            dist_sq = dist**2
            # Sum of squared errors of all points from line passing through pt1 and pt2
            sum_dist_sq = sum_dist_sq + dist_sq
            
    # Mean squared error formula applied
    mean_sq_err = sum_dist_sq / length
    return (mean_sq_err)

Now that the 'line_mse' function is defined, you will be able to run the below lines of code without any error:

# The s_r_lines() function identifies and returns all potential support and 
# resistance line coordinates along with its corresponding mean squared error value.

def s_r_lines(data):
    lines = []
    for pt1 in range(0, len(data) - 1):
        for pt2 in range(0, len(data)):
            if pt1 != pt2:
                mse_val = line_mse(pt1, pt2, data)
                lines.append((data[pt1], data[pt2], mse_val))
    return lines

# Compute and store data of potential support and resistance lines
support_lines = s_r_lines(minima_pts)
resistance_lines = s_r_lines(maxima_pts)

Thank you for letting us know about this as well. 

To avoid any confusion, we will soon update the order of these two code snippets on the blog. 



I hope you found the blog useful. Thanks.