Hi Mayya,
To find the trend lines that intersect at least 3 local highs or lows with a maximum 2% error, you can follow the steps given below.
- Identify Local Highs and Lows: First, you need to identify the local highs and lows in the dataset. Below is a sample code to find local highs in the ‘prices’ vector and store their indices in the ‘extrema’ vector:
if prices(i) > prices(i-1) && prices(i) > prices(i+1)
- Fit a Line Using Minimum number of Points: Select the minimum number of points required from the vector used to store highs(or lows) and fit a line using the corresponding x and y values from these points.
pointsSubset = extrema(i:i+minPoints-1);
xSubset = x(pointsSubset);
pricesSubset = prices(pointsSubset);
- Fit a Linear Trend Line:Use the polyfit function with degree 1 to fit a straight line to the selected points:
p = polyfit(x(points), y(points), 1);
- Error Checking: Calculate the error between the fitted line and the actual data points.
pricesPred = polyval(p, xSubset);
errors = abs((pricesSubset - pricesPred) ./ pricesSubset) * 100;
If the maximum percentage error is less than 2% for all points on the trend line, store the line as a valid result.
if all(errors <= maxError)
trendLines{end+1} = struct('slope', p(1), 'intercept', p(2), 'points', pointsSubset);
For a set of 20 random points, the result can be visualised as figure attached below.
Please refer to the following MATLAB documentation for 'polyfit' and 'polyval' functions.
Hope this solves your query.