How to find lines that intersect at least 3 different points on Y axes with 2 % error range?
이전 댓글 표시
I have time series data which consists of the time and closing prices of a stock. To automatically find trend (or trend like) lines I tried best fit - poly fit (polyfit(x,y,1)). As it is known, lines passing through 3 or more points are considered as trend lines financially and these points must be the lows or highs in the data set. So to be able to find local lows/highs IsChange() function which finds abrupt changes in data seems to be useful. The problem is that after finding local highs (or lows) how to find a line/lines that at least intersect 3 different points with max. 2% error range? Thanks.
답변 (1개)
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:
for i = 2:n-1
if prices(i) > prices(i-1) && prices(i) > prices(i+1)
extrema = [extrema, i]; % Local high
end
end
- 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.
% Calculate the predicted values using the fitted line
pricesPred = polyval(p, xSubset);
% Calculate the error (percentage error) for each point in the subset
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)
% If error is within 2%, store the trend line if it passes 3 points
trendLines{end+1} = struct('slope', p(1), 'intercept', p(2), 'points', pointsSubset);
end
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.
- https://www.mathworks.com/help/matlab/ref/polyfit.html
- https://www.mathworks.com/help/matlab/ref/polyval.html
Hope this solves your query.
카테고리
도움말 센터 및 File Exchange에서 Fit Postprocessing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!