How to find lines that intersect at least 3 different points on Y axes with 2 % error range?

5 ビュー (過去 30 日間)
mayya lcin
mayya lcin 2021 年 3 月 24 日
編集済み: Abhaya 2025 年 1 月 27 日 5:12
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 件)

Abhaya
Abhaya 2025 年 1 月 20 日
編集済み: Abhaya 2025 年 1 月 27 日 5:12
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.
Hope this solves your query.

カテゴリ

Help Center および File ExchangeGet Started with Curve Fitting Toolbox についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by