Next Article in Journal
Stability Analysis and Local Convergence of a New Fourth-Order Optimal Jarratt-Type Iterative Scheme
Previous Article in Journal
Early Detection of Inter-Turn Short Circuits in Induction Motors Using the Derivative of Stator Current and a Lightweight 1D-ResNet
 
 
Font Type:
Arial Georgia Verdana
Font Size:
Aa Aa Aa
Line Spacing:
Column Width:
Background:
Article

Sliding Window-Based Randomized K-Fold Dynamic ANN for Next-Day Stock Trend Forecasting

by
Jaykumar Ishvarbhai Prajapati
and
Raja Das
*
Department of Mathematics, School of Advanced Sciences, Vellore Institute of Technology, Vellore 632014, India
*
Author to whom correspondence should be addressed.
Computation 2025, 13(6), 141; https://doi.org/10.3390/computation13060141
Submission received: 17 April 2025 / Revised: 22 May 2025 / Accepted: 3 June 2025 / Published: 8 June 2025

Abstract

:
The integration of machine learning and stock forecasting is attracting increased curiosity owing to its growing significance. This paper presents two main areas of study: predicting pattern trends for the next day and forecasting opening and closing prices using a new method that adds a dynamic hidden layer to artificial neural networks and employs a unique random k-fold cross-validation to enhance prediction accuracy and improve training. To validate the model, we are considering APPLE, GOOGLE, and AMAZON stock data. As a result, low root mean squared error (1.7208) and mean absolute error (0.9892) in both training and validation phases demonstrate the robust predictive performance of the dynamic ANN model. Furthermore, high R-values indicated a strong correlation between the experimental data and proposed model estimates.

1. Introduction

Trend theory in stock price forecasting is a crucial technical analysis method primarily associated with the price and time domains. A stock trend refers to a specific configuration observed in a stock’s time series chart that signifies a potential price trend. In [1], over 50 extensively recognized stock patterns have been analyzed, and the findings suggest that each stock trend possesses a significant possibility of achieving a forecast price.
In this study, we propose a dynamic artificial neural network (ANN) model integrated with a randomized k-fold cross-validation and adaptive sliding K-day window technique for predicting future stock price trends. The dynamic structure allows the model to vary the number of hidden-layer nodes for each window shift during training, enabling it to autonomously capture underlying patterns in the data. We focus on forecasting the opening and closing prices for the next day and extend the model to predict a sequence of 10 future days using input parameters from historical stock data.
The experimental results show that the proposed dynamic ANN model achieves high predictive accuracy for three major companies, Apple, Google, and Amazon, with rmse and mae metrics reported across training, validation, and overall windows. The model performs competitively compared to conventional architectures such as LSTM and GRU and demonstrates strong adaptability across different window sizes (K = 30 to 80). This supports its generalizability across market conditions and stocks from different sectors.
The motivation behind this approach lies in the limitations of static ANN architectures, which often require manual tuning of parameters. ANNs, unlike traditional linear or nonlinear forecasting models, can automatically learn complex patterns without prior assumptions [2,3,4,5]. However, optimal network design (for example, the number of nodes in the hidden layer) remains challenging. To address this, our proposed architecture incorporates both a sliding window approach and randomized k-fold validation for enhanced generalization and robustness.
The primary contributions of this work are as follows:
  • Providing comprehensive mathematical details regarding the Levenberg–Marquardt (L-M) algorithm for its implementation in the proposed model.
  • Introducing a novel randomized k-fold cross-validation methodology.
  • Developing a new ANN model that incorporates a variable number of nodes in the hidden layer with each K-days window shift.
  • Forecasting the opening and closing prices for the under-researched stocks, along with the correct price trend.
  • Assessing and analyzing the efficacy of the proposed dynamic model in comparison to established advanced models, using performance metrics such as rmse, mae, and R-value.
The paper is segmented into multiple sections: Section 2 provides the research findings based on the literature survey. Section 3 provides a comprehensive explanation of the L-M algorithm: both mathematical and practical implementation approaches and explanation of the revolutionary random k-fold validation combined with the K-day sliding window technique to develop the adaptive neural network construction with the selection of the best system parameters. Section 4 establishes the multiple outcomes and analysis of research work. Section 5 contains a discussion of the study with the practical feasibility of deploying the model. Section 6 reflects the conclusion of the study. Lastly, Appendix A features multiple appendices, containing derivative formulas essential for a comprehensive understanding of the L-M approach.

2. Literature Survey

Buying in equities is the most enticing means of participating in the stock market due to the tremendous rewards; nevertheless, it also carries the extreme trouble of experiencing significant losses. For example, the past performance for the well-known NASDAQ-100 technology index from its inception in 1985-86 shows that successive losing years are extremely rare; in 2022, it fell 33%, followed by a 46% recovery in 2023. Several financial institutions predicted that the index could increase and would go up by 23–24% in 2024 [6,7]. Predicting stock prices is a crucial and sought-after endeavor for investors in the stock market; however, it is also the most difficult challenge due to the volatile nature of stock prices [8]. Consequently, accurate forecasting of stock prices allows investors to enhance returns and mitigate losses [9].
Generally, the stock market is analyzed and predicted using four different methods: technical analysis, fundamental analysis, conventional time series and forecasting techniques, and soft computing approaches. Technical analysis serves as a method for predicting future stock market trends by examining historical time series data on stock prices. Fundamental analysis entails examining a range of metrics related to companies, focusing on aspects that reflect their overall growth, including gain and loss statements, balance sheets, annual reports, and more [10]. Conventional statistical forecasting methodologies encompass time-based models that predict future stock prices by analyzing past stock values using different autoregressive models like ES [11], ARIMA [12], ARCH, and GARCH [13]. Stock price time series data exhibit intricate nonlinear dynamics, significant noise, and dynamic chaos [14]. Machine learning predictions can enhance the efficacy of major regression techniques twofold [15]. In [16], the authors examine the efficacy of deep neural network (DNN) models in forecasting the stock premium. Stock price time series data exhibit intricate nonlinear dynamics, significant noise, and dynamic chaos [17]. Consequently, ordinary methods for forecasting time series cannot effectively capture the intricate nonlinear and non-stationary dynamics of stock markets [18]. The implementation of machine learning-based methodologies in addressing challenges across various research and industrial domains, including optical networks [19], image segmentation [20], internet of things [21], healthcare [22], and logistics [23], has demonstrated superior performance compared to conventional techniques.
Neural network applications possess a fundamental characteristic: a network must undergo training to address a particular problem. The process of iteratively updating the bias and weight in ANNs is referred to as the learning or training of ANNs. Training ANNs involves reducing the total error function, such as the average of squared error, which quantifies the discrepancy between actual and forecasted values averaged across all training samples. Various training algorithms are directly developed from the original back-propagation approach. The back-propagation technique computes and iterates propagated gradients from the output layer of the network to the input layer until the difference between the actual and forecasted values is minimized or other stopping criteria, such as the number of iterations or total number of epochs, are executed [24]. In addition, there are more intricate algorithms that use Newton’s approach, namely the Levenberg–Marquardt (L-M) algorithm, which originally appeared in [25]. It is possible to employ the L-M algorithm with any feedforward neural network since it is a supervised training approach that combines the benefits of the Gauss–Newton method and the gradient descent method [26].
Various neural network training methods such as, the classic L-M algorithm can also become stuck in a local minimum. Secondly, if there are in excess of three layers in the network, the vanishing gradient problem occurs [20]. Classical first-order approaches can address this issue by utilizing the momentum component. This improvement facilitates surpassing local minima and identifying the correct trajectory toward the ideal solution. The momentum factor may be chosen freely and maintained constant throughout the training or be dynamically modified according to the convergence process. This method was described in [27], and the main idea was to combine the good things about the L-M and Conjugate gradient (C-G) approaches to make the training more reliable. In, refs. [28,29,30,31,32], authors endeavored to create two forms of the momentum L-M algorithm, using both fixed and variable momentum sizes. The proposed algorithms were better at cutting down on training time than the traditional L-M algorithm.
As the utilization of ANNs for stock series prediction gains traction, researchers have commenced investigations into its application in stock trend recognition. The study [33] came up with a method to recognize triangular patterns using a recurrent neural network, while [34] developed a way to extract important points and used a multi-output artificial neural network to find stock trends. In [35,36], researchers have used the 10-fold cross-validation approach to validate ANNs and their corresponding models for forecasting diverse trends, including short-term and long-term predictions. Another avenue of investigation involves the segmentation of time series data. In [37], a fixed-length window was employed to segment the time series into subsequences. Then, the time series was shown using the beginning shape patterns that developed [38].
In [39], researchers use a backpropagation ANN with a sliding window method to boost learning over time and make the models more reliable for index forecasting. In [40], the study examines multiple studies that use sliding window approaches inside soft computing models, especially artificial neural networks, to capture short-term fluctuations in the market. In [41], researchers input time-dependent data into several ML models, including ANNs, for directional stock forecasts using a sliding window methodology. The recently created and more popular deep learning networks, LSTM and GRU, outperform ANNs in terms of accuracy [32,42,43,44,45]. This enhanced performance is especially noticeable in applications that use sequential data, such as deep learning and time series prediction. The primary distinction between the shifting window approach and the conventional method is that the former partitions the data into smaller window segments for training and validation, rather than utilizing the entire dataset simultaneously. Subsequently, the previously trained model will be employed to again train and validate the next window segment. Each window segment will be evaluated to forecast stock prices for a certain period. To forecast unseen stock data, the optimum window segment has been finalized after multiple iterations. The issue of significant short-term price fluctuations is effectively managed through the shifting window technique, which facilitates the retraining and updating of the model with each subsequent data prediction.

Problem Statement

Regrettably, all the aforementioned studies employed static methodologies, and the input data consisted of long-term sequences. Static approaches are unsuitable for stock investment due to the time-consuming nature of stock time series, where long-term sequences incur significant computational costs in dynamic methods. Furthermore, the model will consistently incorporate the initial parameters, although their impact on prediction decreases over time. So, from the extensive literature survey, we propose a dynamic methodology aimed at identifying recently formed stock pattern trends, enabling executable investment decisions based on stock series patterns and forecasting the opening and closing prices with limited data.

3. Methodology

3.1. Mathematical Derivation of Levenberg–Marquardt Algorithm

The derivation of the L-M algorithm [25] is contingent upon the prior derivation of the following algorithms: the steepest descent technique (see Appendix A.1), Newton’s technique (see Appendix A.2), and the Gauss–Newton technique (see Appendix A.3).
Before deriving the L-M algorithm, we define multiple frequently utilized indices. Let p denote the sequence index, which varies from 1 to P , with P indicating the total number of samples. m signifies the output index, ranging from 1 to M , with M indicating the total number of outputs. For weight, consider i and j indices, spanning from 1 to N , where N denotes the total number of weights, and lastly, k indicates the iteration index.
The error (loss) function has been determined to assess the training procedure. We calculate the total error function for all training sequences and network outputs as:
L ( x , w ) = 1 2 p = 1 P m = 1 M l p , m 2
where x represents the input vector, w denotes the weight vector, and l p , m signifies the training error at output m while using the sequence p, defined as
l p , m = y p , m y ^ p , m
where y p , m is the desired output vector and y ^ p , m is the actual output vector.

Levenberg–Marquardt Algorithm

From the Appendix A, to ensure the invertibility of the estimated the Hessian matrix J T J , the L-M method offers an alternative estimated of the Hessian matrix:
H J T J + μ I
where μ is a value greater than zero, referred to as the combination coefficient, and I is the identity matrix.
The elements of the approximated matrix H that are on the main diagonal will be greater than zero, as shown in Equation (3). We can be sure that matrix H is always invertible with this approximation (3). The revised L–M method can be expressed through incorporating Equations (A21) and (3):
w k + 1 = w k ( J k T J k + μ I ) 1 J k T l k
The L–M method is an adaptation of the S-D technique and the Gauss–Newton technique. During training, it changes between the two algorithms. Equation (4) is getting close to Equation (A21) and the Gauss–Newton technique is used when the combination coefficient is very small or almost zero. Equation (4) gets close to Equation (A2) when the combination coefficient is significantly big, and so the S-D technique is employed.
A large μ in Equation (4) can be considered analogous to the learning coefficient in the S-D technique (A2):
β = 1 μ
The method is iteratively run until the loss factor decreases to a minimal threshold number, at which time the desired result and actual output are nearly equal. However, it is crucial to emphasize that the network must be trained with a large enough number of samples and iterations to obtain the desired outcomes.
Choosing the μ Value in Levenberg–Marquardt Algorithm: The μ parameter in the L-M method regulates the equilibrium between the S-D and Gauss–Newton techniques. A larger μ value produces a step approaching the S-D technique, while a minimal μ value yields a step closer to the Gauss–Newton technique.
Here, we are defining the strategies for choosing the μ value:
  • Initial value: Start with a moderate value: A common starting point is μ = 1 . Adjust based on problem characteristics: If the problem is known to be highly nonlinear, a larger initial value might be appropriate.
  • Adaptive Updates:
    (i) Increase μ if the step size is not improving: If the sum of squared residuals increases after a step, it indicates that the step size could be too large. Increase μ to take a smaller and more cautious step.
    (ii) Decrease μ if the step size is consistently improving: If the sum of squared residuals decreases consistently after multiple steps, it suggests that the step size is appropriate. Decrease μ to allow for larger steps.

3.2. Data Collection

This research utilizes datasets from three distinct companies across various industries, specifically AMAZON, APPLE, and GOOGLE, which are listed on the NASDAQ Stock Market, United States of America (U.S.A) and included in the S & P 500 Index, covering the period from 1 January 2022 to 31 December 2022. To ensure the reliability and validity of the proposed dynamic model, we have considered complementary data from the Yahoo Finance website (https://finance.yahoo.com/) accessed on 2 March 2025 for the stocks AMAZON, APPLE, and GOOGLE over a period of 251 days (the market remained closed on holidays and festivals) on a daily basis, consisting of five individual parameters: opening price, closing price (adjusted closing price), day’s high price, day’s low price, and volume. To perform this experiment, we simulate data and produce graphs in the MATLAB R2024a environment.

3.3. Normalization

Numerous machine learning algorithms endeavor to identify patterns within datasets through the comparison of data point attributes. Nevertheless, a problem arises when the characteristics exhibit significant disparities in their scales. Normalization encompasses a range of strategies used for data processing, especially when the data comes from different scales. If normalization is not applied, it may lead to errors in evaluation or inappropriate conclusions. So, for that we are using Min-Max normalization. This technique involves the process of normalizing the input dataset by fitting it within a predetermined boundary, specifically within a predefined period. The values of numeric variables are within the range of 0 to 1.
To normalize variable x i ˜ into x i , the formula of Min-Max normalization is given by
x i = ( 1 0 ) ( x i ˜ x m i n ˜ ) ( x m a x ˜ x m i n ˜ ) + 0
and so,
x i = ( x i ˜ x m i n ˜ ) ( x m a x ˜ x m i n ˜ ) .
where x m a x ˜ = Maximum of x i ˜ among dataset, x m i n ˜ = Minimum of x i ˜ among dataset. All elements of each row are considered to be non-equal, and x i ˜ has only finite real values. (If x m a x ˜ = x m i n ˜ or if x m a x ˜ of x m i n ˜ are not finite, then x i = x i ˜ and there is no change.)
In this study, before feeding input variables to the neural network, we normalize all the input variables into the range [0, 1].

3.4. Artificial Neural Networks

To enhance the understanding of forward and backward calculations, let us consider the two-layer ANN as shown in Figure 1, having an input layer with x i ( i = 1 , 2 , , n represents the i-th input neuron). The hidden layer with h j ( j = 1 , 2 , , m represents the j-th hidden neuron), the sigmoid activation function f h ( · ) , and output layer with y o ( o = 1 , 2 , , l represents the o-th output neuron) and linear activation function f o ( · ) . Where weight-and-bias notations can be understood as follows: w i j is the weight connecting input neuron i to hidden neuron j, b j is the bias of hidden neuron j, v j o is the weight connecting hidden neuron j to output neuron o, and c o is the bias of output neuron o. For a given sequence, n = 25 , l = 2 , and m are variable between 1 and 30.
Our problem can be described as follows: The input layer of the ANN consists twenty-five variables of the stocks’ opening price, closing price, volume, daily high, and daily low price for five consecutive days. The variables x 1 , x 2 , x 3 , x 4 , and x 5 represent inputs for the day t; x 6 , x 7 , x 8 , x 9 , and x 10 denote inputs for the day t 1 ; x 11 , x 12 , x 13 , x 14 , and x 15 correspond to inputs for the day t 2 ; x 16 , x 17 , x 18 , x 19 , and x 20 signify inputs for the day t 3 ; and x 21 , x 22 , x 23 , x 24 , and x 25 indicate inputs for the day t 4 .
The forward calculation may be structured as follows:
(a)
Compute the net value at the j t h hidden node and outputs for all nodes in the hidden layer:
z j = i = 1 n w i j x i + b j
h j = f h ( z j ) = 1 1 + e z j .
So,
h 1 h 2 h m = f h w 1 , 1 w 1 , 2 w 1 , 25 w 2 , 1 w 2 , 2 w 2 , 25 w m , 1 w m , 2 w m , 25 x 1 x 2 x 25 + b 1 b 2 b m
(b)
Utilize the first-layer neurons’ outputs as the inputs for every neuron in the output layer, calculate the net values for the k t h output node in a similar manner, and output from them can be expressed as:
o k = j = 1 m v j o h j + c o
y k = f o ( o o )
Therefore,
y 1 y 2 = f o v 1 , 1 v 1 , 2 v m , 1 v 2 , 1 v 2 , 2 v m , 2 h 1 h 2 h m + c 1 c 2
(c)
Calculate the loss function which is defined in Equations (1) and (2). After the forward calculation, The Jacobian, along with the loss vector and the damping parameter μ , is used in the L-M update rule to calculate how much to adjust each weight in the network.
The backward calculation may be structured as follows:
(d)
The matrix J has dimensions ( P · M ) × N , where P is the number of training sequences, M is the number of output neurons, and N is the total number of biases and weights in the network. Therefore, for the p t h training sequence with the m t h output neuron and the n t h weight/bias, the entry in the matrix J will be:
l p , m w N = l p , m y m y m s m s m w N
where l p , m is the loss vector for the p t h sequence and the m t h output neuron, y m is the output of the m t h output neuron, s m is the weighted sum of inputs to the m t h output neuron.
(e)
Back-propagation from the output layer to the hidden layer: If w n is a weight connecting the hidden layer to the output layer ( v j k ), then:
s m v j o = h j ( output for the j t h hidden node )
Back-propagation from the hidden layer to the input layer: If w n is a weight connecting the input layer to the hidden layer ( w i j ), then:
s m w i j = s m h j h j z j z j w i j
= v j k f h ( z j ) x i
(f)
After the calculating the back-propagation at each layer, the L-M update:
Δ w = ( J T J + μ I ) 1 J T l
where Δ w is the vector of weight-and-bias updates, J is the Jacobian matrix (with dimensions P · M × N ), μ is the damping parameter, I is the identity matrix, and l is the vector of errors ( t p , m y p , m ) for all training patterns p and output neurons m .
(g)
Update the rule for new weights and biases as:
w = w + Δ w , b = b + Δ b .
The stages (e)–(g) are repeated for backward propagation. Then, the related parts of the matrix J can be found using Equation (13). By performing the forward and backward calculations as mentioned above, we can compute the entire matrix J for other sequences.

3.5. Training Process Design

If the loss value decreases, which means it is smaller than the last loss value, it implies that the quadratic approximation on the total loss function is working and the combination coefficient μ could be reduced to reduce the influence of the gradient descent part (ready to speed up). If the loss value grows, indicating it surpasses the previous loss value, it is essential to adhere more closely to the gradient to identify an appropriate curvature for quadratic estimation, necessitating an increase in the value of μ .
Therefore, the training process using the L–M algorithm is as per the following steps:
  • Assess the total loss value using the first obtained random weights.
  • Execute an update as specified by Equation (4) to modify weights.
  • Utilize the updated weights to compute the overall loss value.
  • If the updated total loss value increases, reverse the step (restore the weight vector to its prior value) and boost μ by a factor of 10. Proceed to step 2 and attempt the update once again.
  • If the updated total loss value is lower, accept the step by retaining the new weight vector as the current one and reduce μ by a factor of 10.
  • Proceed to step 2 with the updated weights until the current overall loss value is less than the specified threshold.
  • For regularization: We keep an eye on validation performance, and if the loss function stagnates or gets worse over the sequence of six iterations, we halt the training to prevent becoming stuck at local minima.
The flow chart for the forward and backward calculations, as well as the training process, is illustrated in Figure 2.

3.6. Random k-Fold Cross-Validation

The technique of multi k-fold validation is used to evaluate predictive models. It is a resampling technique that evaluates and trains a model over several iterations using distinct data folds. Figure 3a illustrates the division of the dataset into k-folds, or subsets of equal size. The model is trained and analyzed k times, each time with a different fold as the validation set. This method facilitates model evaluation, selection, and hyperparameter tuning by providing a more solid measure of a model’s effectiveness. Previous research has employed k-fold cross-validation to avoid overfitting. The dataset is divided into two parts: 80% for training the model and 20% for validating it. This improves the algorithm’s generalization capabilities in various aspects. But, for the stock market data, traditional k-fold cross-validation is not useful, as standard k-fold randomly splits a big portion of the data, which violates the time order and can cause data leakage.
To overcome the drawbacks of traditional k-fold cross-validation, this study develops a novel random multi k-fold validation to improve the algorithm. It enhances how well the model predicts unknown data based on the known dataset, which helps avoid a problem called “overfitting”. The presence of overfitting indicates that the model did not learn the important laws in the data. A random multi k-fold validation takes a more dynamic strategy, randomly splitting the data into smaller subsets for training and validation in each cycle. This strategy improves the robustness of model evaluation by removing the potential bias associated with fixed splits and allows for a more comprehensive assessment of the algorithm’s effectiveness across varied data distributions. By setting a random number seed to ensure the same number of samples for each data split, the consistency of cross-validation is ensured. Figure 3b shows the procedure for partitioning and training the sample set. This method employs a random approach to create a sample set, allocating 15% for validation and 85% for training data. A random k-fold cross-validation facilitates the model’s learning from diverse samples, thereby mitigating the risk of converging to local extrema.

3.7. Sliding Window Technique

The sliding window technique, employing a window size of ‘K–days’ and a 10–day interval, is utilized to transform raw time series data into sequential input features for the ANN. This method enables the ANN to identify temporal dependencies and trends in the data, thereby improving its predictive efficacy. By methodically adjusting the window, the model can acquire insights from diverse segments of the data, enhancing its precision in predicting future values. Each window comprises ‘K’ consecutive data values, representing ‘K’ days of observation. The observations are subsequently normalized and input into the ANN, allowing it to identify patterns and correlations that may not be apparent in the raw data alone. As the model processes these inputs, it adjusts its weights and biases, resulting in more accurate predictions grounded in historical trends. The model subsequently forecasts for the ensuing 10 days. The window subsequently shifts by 10 days, resulting in the revised ‘K’ day dataset. For instance, utilizing daily data and K = 30, the initial window encompasses days 1–30, followed by window shifts of days 2–31, 3–32, and so forth. This 10-day period facilitates a comprehensive analysis of the data, revealing trends that persist beyond multiple days. For a better understanding of the sliding window mechanism, refer to Figure 4. As for each window shift, we train the data, and based on the MSE value, we try to identify the best neural network architecture to predict next day opening and closing price of the stock. This iterative process enables us to enhance our model by modifying parameters and assessing performance with each new window. Our objective is to improve predictive accuracy and ensure that the architecture aligns with the underlying patterns in the dataset.

3.8. Selection Criteria for Nodes in Hidden Layer for the Dynamic Neural Network Architecture

Initially, we fixed the K-day window size, and for each window shift, we determined the k-th fold for which the ANN architecture would be developed, and then we varied the number of nodes in the hidden layer to select the optimum ANN architecture. The architecture comprises 25 input neurons in the input layer and 2 output neurons in the output layer, with the hidden layer containing 1, 2, 3, … up to 30 neurons. We construct all plausible ANN structures. The neural network architecture for all combinations will be represented as 25-1-2, 25-2-2, …, 25-29-2, and 25-30-2. So, the total number of possible ANN architectures would be 10 × 30 = 300 for each shift. Therefore, we have up to 300 × 21 = 6300 different ANN model combinations for each K-window size, depending on the fold and number of nodes in the hidden layer. Subsequently, we evaluate the mean square error (mse), which is the loss function for each ANN having a different architecture. From there, we select the optimal architecture with the least overall root mean squared error (rmse), mean absolute error (mae), and R-value. Subsequently, we repeat this process for each fold, selecting the optimal combination of fold and number of nodes in the hidden layer. Through comparison of overall performance metric values across various configurations, we determine the optimal architecture for each window shift that mitigates the error and improves model reliability. Figure 5 demonstrates the flowchart of the selection criteria for the optimal number of nodes in the hidden layer and the number of k-folds in determination of the best dynamic architecture for the ANN.
Performance metrics, including rmse, mae, and R-value, are evaluated for each K-window size for APPLE, GOOGLE, and AMAZON. The K = 70 window size demonstrated enhanced performance for APPLE compared to alternative window sizes. Table 1 shows the performance results for APPLE stock for each shift of the artificial neural network, taking into account the number of nodes in the hidden layer, the random k-fold value, and the K = 70 window size. The K = 40 window size demonstrated enhanced performance for GOOGLE compared to the other window sizes. Table 2 displays the performance data for GOOGLE stock associated with each shift of the artificial neural network, considering the nodes in the hidden layer and the random k-fold value along with the K = 40 window size. Similarly, the K = 60 window size demonstrated superior performance for AMAZON compared to other window sizes. Table 3 shows the performance results for AMAZON stock based on each shift in the artificial neural network, taking into account the nodes in the hidden layer and the random k-fold value within the K = 60 window size.
Figure 6 demonstrates the dynamic architecture of the ANN with the highest accuracy of folds in each window shift, where the number of nodes in the hidden layer changes ranging from 1 to 30. This adaptability allows the model to effectively capture temporal patterns and fluctuations in stock prices. The results also demonstrate that incorporating the optimal number of nodes with high accuracy folds in the hidden layer significantly enhances the accuracy of predictions. This shows how important it is to fine-tune model parameters in financial forecasting.

4. Results

In this study, we focus on the following analysis: (i) measuring the accuracy of the predicted pattern trend to the actual pattern trend and (ii) actual versus forecasted opening and closing price by optimal K-day window size for the abovementioned stocks. For the first analysis, we define the actual pattern trend as the difference between the day’s closing price and the opening price, and the predicted pattern trend as the difference between the next day’s predicted closing price and the predicted opening price. If this difference is positive, then we call it an “upward trend,” and its sign will be positive; otherwise, we call it a “downward trend,” and its sign will be negative. The results of this comparison will allow us to evaluate the efficacy of our dynamic neural network and discover any differences between our forecasts and the actual short-term market trend behavior.
Let us define the following terms to understand the pattern trend analysis as follows:
  • Predicted trend of the ( t + 1 ) day on the day t, defined as:
    ( P T ) = Predicted closing price of ( t + 1 ) day − Predicted opening price of ( t + 1 ) day.
  • Actual trend of the ( t + 1 ) day, defined as:
    ( A T ) = Actual closing price of the ( t + 1 ) day − Actual opening price of the ( t + 1 ) day.
  • Correct pattern prediction ( C P ) :
    (a)
    Case 1: Same direction: If sign ( A T ) = sign ( P T ) , then:
    C P = 1 ( Correct prediction )
    (b)
    Case 2: Opposite direction, within tolerance (T) level: If sign ( A T ) sign ( P T ) and A T 0 and ( | P T | + | A T | ) T , then:
    C P = 1 ( Correct prediciton )
    (c)
    Case 3: Opposite direction, beyond tolerance (T): If sign ( A T ) sign ( P T ) and A T 0 and ( | P T | + | A T | ) > T , then:
    C P = 0 ( Incorrect prediction )
    (d)
    Case 4: AT is zero: If A T = 0 , then if P T = 0 then C P = 1 else C P = 0 .
  • Total number of predictions ( T P ) =
    Total number of correct predictions ( C P = 1 )
                     +
    Total number of incorrect predictions ( C P = 0 ) .
With the above four conditions, we will find the accuracy of the correct prediction trend one day before the actual trend as follows:
% of accuracy for correct predicting trend = Total number of C P = 1 T P × 100 .
By analyzing these discrepancies, investors could create buying and selling strategies for ( t + 1 ) -th day on the t -th day. As an example, if the difference between the next day’s predicted closing price and predicted opening price is significantly large (upward trend), then the investor can buy stocks in bulk at the next day’s market opening time and book a profit at the end of the day. If the difference is considerably negative (downward trend), avoid the deal for the following day. Here, we set the tolerance to 2.5 % , which is equal to ± 1.25 % of the closing price of the previous day. It indicates that if the trade price does not exhibit a substantially larger movement (sideways trend), it will not cause a major loss or profit for the investor. This strategy allows investors to minimize risk while maximizing potential gains. For this, we are analyzing the accuracy of correct predicted pattern trends in % for every K-day window size while considering the abovementioned four cases.
Table 4 presents the accuracy (in percentage) level of a dynamic ANN to predicting the next day’s pattern trend for three different stocks: AMAZON, GOOGLE, and APPLE. The accuracy is measure for all K-window sizes to predict correct pattern trend for next day. For the AMAZON stock, K = 60 days window size predicts correct predicted trend with highest accuracy of 71.11 % . For the GOOGLE stock, K = 40 days window size predicts correct predicted trend with highest accuracy of 73 % and lastly, for the APPLE stock, K = 70 days window size predicts correct predicted trend with highest accuracy of 75.29 % .
Figure 7 demonstrates how the actual versus predicted trends match each other for the abovementioned stocks. Figure 7a for AMAZON represents the actual vs. predicted trend with the window size K = 60 and 71.11 % accuracy. Similarly, Figure 7b,c represent, for APPLE and GOOGLE stock, the actual trend vs. the predicted trend of window size K = 70 and K = 40 with 75.29 % and 73.0 % accuracy, respectively.
Figure 8 illustrates the actual versus predicted (i) opening prices (Figure 8a,c,e) and (ii) closing prices (Figure 8b,d,f) for the abovementioned stocks across the dataset. The analysis employs window sizes K = 60, 70, and 40 days for AMAZON, APPLE, and GOOGLE, respectively, as these sizes yield the most accurate predictions for the subsequent day. Quantitative metrics such as rmse and regression line (R) are crucial for evaluating time series forecasting models; nevertheless, they often provide an aggregated and potentially incomplete representation of a model’s predictive capacity. This metric is crucial for assessing error magnitude; however, they can mask significant performance trends and lack the ability to pinpoint precise forecasts. Regression line plots, in particular, show the correlation between the model’s predicted and actual values in forecasting evaluation.
Figure 9 represents the regression line for the actual versus predicted variable for opening prices (Figure 9a,c,e) and for closing prices (Figure 9b,d,f) across the dataset. The analysis employs window sizes K = 60, 70, and 40 days for AMAZON, APPLE, and GOOGLE, respectively, as these window sizes yield the most accurate predictions for the subsequent day. This graph aligns the model’s output with actual data on a point-by-point basis, bypassing scalar error metrics. A model exhibiting a slope about equal to 1 and an intercept close to 0 can be considered unbiased. On the other hand, if the model consistently overestimates or underestimates values, and there is a lot of variation in the points, it shows where the model does not accurately represent the time series data. Regression line plots can reveal localized performance patterns that aggregated error measures fail to capture. A model with a low mean squared error might seem effective overall, but a regression line plot can show specific points where the model’s predictions often differ from the real values.

5. Discussion

After a well-tuned refining process that included data normalization, variable K-day sliding window shifts, and randomized k-fold validation for each fold with ANN training using the L-M algorithm, the proposed model shows better accuracy over existing models such as LSTM (Long Short-Term Memory) and GRU (Gated Recurrent Unit) by consistently generating significantly lower rmse and mae values as per the Table 5. Also, Table 4 shows that the proposed dynamic model achieved the highest accuracy for APPLE with a window size of K = 60, GOOGLE with K = 40, and Amazon with K = 70. Upon determining appropriate K-window sizes for the respective stocks and applying them to unseen data, the model yields accurate predictions for the next day’s price trend: APPLE with 71.11%, GOOGLE with 73%, and AMAZON with 75.29%. Apart from the low rmse and mae values, the high R values for AMAZON, APPLE, and GOOGLE are 0.9545, 0.9491, and 0.9820, respectively, indicating a strong correlation between the predicted and actual values.
Despite the abovementioned strengths, the current model relies solely on historical OCHLV (open, close, high, low, and volume) data as input parameter, which, while valuable for capturing internal market dynamics, fails to account for external factors that often drive stock price movements. Critical influences such as political developments, economic announcements, earnings reports, and news sentiment are excluded. These exogenous and often unstructured variables may have a significant nonlinear effect on price trends. The absence of such contextual data limits the model’s adaptability during sudden or sentiment-driven market shifts. To address this limitation, future work could involve the integration of alternative data sources such as financial news sentiment, macroeconomic indicators (e.g., interest rates, CPI), and technical indicators such as RSI and MACD. Since the proposed model provided a certain level of accuracy in forecasting trends, it also provides a glimpse into future possibilities for integrating the dynamic model with more complex optimizers.

Practical Feasibility of Deploying the Model

Although the proposed model involves dynamic architectural adjustments and randomized k-fold cross-validation, the overall computational load remains manageable. We conducted this experiment using MATLAB R2024a on an Apple M1 chip with 8GB RAM, typically completing each window shift in a shorter time. Importantly, once the model is trained, real-time prediction requires only forward propagation, which is computationally lightweight. The model maintains a computational structure that is practical for real-time or near real-time deployment, as forecasts can be performed efficiently post market close, while retraining can be scheduled during off-market hours, ensuring uninterrupted forecasting service with minimal latency. Furthermore, real-time stock market data can be readily accessed through public APIs such as Yahoo Finance, enabling seamless integration of the model into a real-time forecasting pipeline. This integration, coupled with the model’s efficient forecast and retraining strategy, supports its practical deployment in operational environments.

6. Conclusions

In comparison to the current LSTM and GRU models on the study of under-researched stocks, the proposed dynamic model provides the highest accuracy in terms of the rmse and mae values following the well-tuned refining process, which includes data normalization, variable K-sized sliding windows, and randomized k-fold validations on each fold to determine the ideal number of nodes in the hidden layer of the ANN using the L-M algorithm. This approach not only enhances the model’s predictive performance but also ensures robustness against overfitting. As a result, the dynamic model demonstrates superior capabilities in capturing the correct price trend for the next day.
So, as future work, the integration of dynamic ANNs with the sliding window technique demonstrates broad applicability across various sectors, including finance, gas, oil, commodity, and currency exchanges. Additionally, transitioning to hybrid or ensemble architectures like ANN-LSTM, ANN-GRU, or ANN-XGboost would allow the model to better capture both short-term fluctuations and long-term dependencies in time series while also incorporating memory of past external events. We can extend this innovative approach to forecast cyberattack moments in security defense systems, as well as in the healthcare system. Future efforts will focus on improving the proposed technique and expanding its application across these areas.

Author Contributions

Conceptualization, methodology, writing—original draft preparation, formal analysis, investigation, writing—review and editing by J.I.P.; visualization, supervision, validation, software by R.D. Both authors have contributed equally to this work. All authors have read and agreed to the published version of the manuscript.

Funding

This research received no external funding.

Informed Consent Statement

Not applicable.

Data Availability Statement

The datasets used and/or analyzed during the current study were obtained from Yahoo Finance website (https://finance.yahoo.com/) accessed on 2 March 2025 and are available from the corresponding author upon reasonable request.

Acknowledgments

The authors express gratitude to the Department of Mathematics, School of Advanced Sciences, Vellore Institute of Technology, Vellore, India, for facilitating the research at the FIST Lab (SR/FST/MS-II/2023/139), which is funded by the Department of Science and Technology (DST), Government of India. Furthermore, the authors extend gratitude to the anonymous reviewers and editors for their constructive feedback and insightful comments, which have significantly improved this manuscript. Their expertise and dedication have significantly enhanced our work.

Conflicts of Interest

The authors have equally contributed and given their consent for publication. Furthermore, the authors affirm that they have no competing interests. The authors additionally state that they possess no identifiable competing financial interests or relationships that may have seemed to influence the work presented in this study.

Appendix A

Appendix A.1. Steepest Descent Algorithm (S-D)

The steepest descent algorithm (S-D) is categorized as a first-order partial derivative algorithm. It utilizes the first-order derivative of the total loss function for determining the minima within the loss space. The gradient g is frequently characterized as the first-order derivative of the total loss function in (1):
g = L ( x , w ) w = L w 1 L w 2 L w N T
Utilizing the concept of gradient g in (A1), the iterative rule for the steepest descent method can be defined as
w k + 1 w k = β g k
The learning constant, denoted by β , is the step size.

Appendix A.2. Newton’s Method

Newton’s method presupposes that all gradient components g 1 , g 2 , , g N are functions of the weights and that all weights are linearly independent.
g 1 = F 1 ( w 1 , w 2 , , w N ) g 2 = F 2 ( w 1 , w 2 , , w N ) g N = F N ( w 1 , w 2 , , w N )
where F 1 , F 2 , …, F N represent nonlinear correlations between weights and their corresponding gradient vector.
Expand each g i ( i = 1 , 2 , , N ) in Equations (A3) using a Taylor series first-order approximation:
g 1 g 1 , 0 + g 1 w 1 Δ w 1 + g 1 w 2 Δ w 2 + + g 1 w N Δ w N g 2 g 2 , 0 + g 2 w 1 Δ w 1 + g 2 w 2 Δ w 2 + + g 2 w N Δ w N g N g N , 0 + g N w 1 Δ w 1 + g N w 2 Δ w 2 + + g N w N Δ w N
By incorporating the definition of the gradient vector g in (A1), it can be determined that
g i w j = L w i w j = 2 L w i w j
By substituting Equation (A5) into Equation (A4):
g 1 g 1 , 0 + 2 L w 1 2 Δ w 1 + 2 L w 1 w 2 Δ w 2 + + 2 L w 1 w N Δ w N g 2 g 2 , 0 + 2 L w 2 w 1 Δ w 1 + 2 L w 2 2 Δ w 2 + + 2 L w 2 w N Δ w N g N g N , 0 + 2 L w N w 1 Δ w 1 + 2 L w N w 2 Δ w 2 + + 2 L w N 2 Δ w N
In contrast to the steepest descent approach, the second-order derivatives of the total loss function must be computed for each element of the gradient vector. To achieve the minima of the total loss function L, each component of the gradient vector must equal zero. Consequently, the left sides of Equations (A6) are all null, and then
0 g 1 , 0 + 2 L w 1 2 Δ w 1 + 2 L w 1 w 2 Δ w 2 + + 2 L w 1 w N Δ w N 0 g 2 , 0 + 2 L w 2 w 1 Δ w 1 + 2 L w 2 2 Δ w 2 + + 2 L w 2 w N Δ w N 0 g N , 0 + 2 L w N w 1 Δ w 1 + 2 L w N w 2 Δ w 2 + + 2 L w N 2 Δ w N
By equating Equation (A1) with (A7)
L w 1 = g 1 , 0 = 2 L w 1 2 Δ w 1 + 2 L w 1 w 2 Δ w 2 + + 2 L w 1 w N Δ w N L w 2 = g 2 , 0 = 2 L w 2 w 1 Δ w 1 + 2 L w 2 2 Δ w 2 + + 2 L w 2 w N Δ w N L w N = g N , 0 = 2 L w N w 1 Δ w 1 + 2 L w N w 2 Δ w 2 + + 2 L w N 2 Δ w N
There exist N equations corresponding to N parameters, enabling the calculation of all Δ w i . The solutions enable iterative updates to the weight space. Equation (A8) may alternatively be expressed in matrix form:
g 1 g 2 g N = L w 1 L w 2 L w N = L 2 w 1 2 L 2 w 1 w 2 L 2 w 1 w N L 2 w 2 w 1 L 2 w 2 2 L 2 w 2 w N L 2 w N w 1 L 2 w N w 2 L 2 w N 2 Δ w 1 Δ w 2 Δ w N
where the square matrix can be denoted as Hessian matrix:
H = L 2 w 1 2 L 2 w 1 w 2 L 2 w 1 w N L 2 w 2 w 1 L 2 w 2 2 L 2 w 2 w N L 2 w N w 1 L 2 w N w 2 L 2 w N 2
Adding Equation (A1) and (A10) with Equation (A9), we have
g = H Δ w
Therefore,
Δ w = H 1 g
So, the update rule for Newton’s technique can be written as
w k + 1 w k = H k 1 g k
The Hessian matrix H , representing the second-order derivatives of the total loss function, offers a precise evaluation of the gradient vector’s variation. Comparing Equations (A2) and (A13) provides that suitably aligned step sizes are generated by the inverse of the matrix H .

Appendix A.3. Gauss–Newton Method

Utilizing Newton’s method for weight adjustment necessitates the calculation of the matrix H , which involves determining the second-order derivatives of the total loss function, a process that may be rather complex. To simplify the calculation procedure, the Jacobian matrix J is defined as
J = l 1 , 1 w 1 l 1 , 1 w 2 l 1 , 1 w N l 1 , 2 w 1 l 1 , 2 w 2 l 1 , 2 w N l 1 , M w 1 l 1 , M w 2 l 1 , M w N l P , 1 w 1 l P , 1 w 2 l P , 1 w N l P , 2 w 1 l P , 2 w 2 l P , 2 w N l P , M w 1 l P , M w 2 l P , M w N
Combining (1) and (A1), components of the g can be evaluated as:
g i = L w i = 1 2 p = 1 P m = 1 M l p , m 2 w i = p = 1 P m = 1 M l p , m w i l p , m
By adding Equations (A14) and (A15), the correlation between the matrix J and g is established as follows:
g = J l
where the loss vector l can be given as:
l = l 1 , 1 l 1 , 2 l 1 , M l P , 1 l P , 2 l P , M
The element located in the j-th column and i-th row of the Hessian matrix H could be determined by substituting Equation (1) into Equation (A10):
h i , j = 2 L w i w j = 2 1 2 p = 1 P m = 1 M l p , m 2 w i w j = p = 1 P m = 1 M l p , m w i l p , m w j + S i , j
where S i , j is
S i , j = p = 1 P m = 1 M 2 l p , m w i w j l p , m
Given that the core idea of Newton’s technique postulates that S i , j tends to zero, the correlation between the matrix H and J may be reformulated as
H = J T J
The revised formula for the Gauss–Newton technique can be derived from incorporating Equations (A13), (A16), and (A20):
w k + 1 = w k ( J k T J k ) 1 J k T l k
It is clear that in comparison to Newton’s technique (A13), the Gauss–Newton technique is better because it does not need to calculate higher-order derivatives for the total loss function. Instead, it uses the matrix J . The Gauss–Newton technique encounters the same invertibility issue as the Newton technique. From a mathematical perspective, the issue can be viewed as the potential invertibility of the matrix J T J .

References

  1. Bulkowski, T.N. Encyclopedia of Chart Patterns; John Wiley & Sons: Hoboken, NJ, USA, 2021. [Google Scholar]
  2. Tealab, A. Time Series Forecasting Using Artificial Neural Networks Methodologies: A Systematic Review. Future Comput. Inform. J. 2018, 3, 334–340. [Google Scholar] [CrossRef]
  3. Smith, J.S.; Wu, B.; Wilamowski, B.M. Neural Network Training with Levenberg–Marquardt and Adaptable Weight Compression. IEEE Trans. Neural Netw. Learn. Syst. 2018, 30, 580–587. [Google Scholar] [CrossRef]
  4. Han, H.; Liu, Z.; Barrios Barrios, M. Time series forecasting model for non-stationary series pattern extraction using deep learning and GARCH modeling. J. Cloud Comput. 2024, 13, 2. [Google Scholar] [CrossRef]
  5. Zhang, Y. Deep learning models for price forecasting of financial time series: A review of recent advancements: 2020–2022. WIREs Data Min. Knowl. Discov. 2024, 14, e1519. [Google Scholar] [CrossRef]
  6. Zhan, Z.; Kim, S.K. Versatile Time-Window Sliding Machine Learning Techniques for Stock Market Forecasting. Artif. Intell. Rev. 2024, 57, 209. [Google Scholar] [CrossRef]
  7. May, B. A soft landing may be in sight, but expect turbulence. Econ. Outlook 2024, 48, 29–32. [Google Scholar] [CrossRef]
  8. Jahan, I.; Sajal, S.Z.; Nygard, K.E. Prediction Model Using Recurrent Neural Networks. In Proceedings of the 2019 IEEE International Conference on Electro Information Technology (EIT), Brookings, SD, USA, 20–22 May 2019; IEEE: Piscataway, NJ, USA, 2019; pp. 1–6. [Google Scholar] [CrossRef]
  9. Pai, P.F.; Liu, C.H. Predicting Vehicle Sales by Sentiment Analysis of Twitter Data and Stock Market Values. IEEE Access 2018, 6, 57655–57662. [Google Scholar] [CrossRef]
  10. Yang, F.; Chen, Z.; Li, J.; Tang, L. A Novel Hybrid Stock Selection Method with Stock Prediction. Appl. Soft Comput. 2019, 80, 820–831. [Google Scholar] [CrossRef]
  11. Chouhan, S.S.; Kaul, A.; Singh, U.P. Image Segmentation Using Computational Intelligence Techniques: Review. Arch. Comput. Methods Eng. 2019, 26, 533–596. [Google Scholar] [CrossRef]
  12. Adebiyi, A.A.; Adewumi, A.O.; Ayo, C.K. Comparison of ARIMA and Artificial Neural Networks Models for Stock Price Prediction. J. Appl. Math. 2014, 2014, 614342. [Google Scholar] [CrossRef]
  13. Kristjanpoller, W.; Minutolo, M.C. A hybrid volatility forecasting framework integrating GARCH, artificial neural network, technical analysis and principal components analysis. Expert Syst. Appl. 2018, 109, 1–11. [Google Scholar] [CrossRef]
  14. Sakhre, V.; Singh, U.P.; Jain, S. FCPN Approach for Uncertain Nonlinear Dynamical System with Unknown Disturbance. Int. J. Fuzzy Syst. 2017, 19, 452–469. [Google Scholar] [CrossRef]
  15. Gu, S.; Kelly, B.; Xiu, D. Empirical Asset Pricing via Machine Learning. Rev. Financ. Stud. 2020, 33, 2223–2273. [Google Scholar] [CrossRef]
  16. Zhou, X.; Zhou, H.; Long, H. Forecasting the Equity Premium: Do Deep Neural Network Models Work? Mod. Financ. 2023, 1, 1–11. [Google Scholar] [CrossRef]
  17. Atsalakis, G.S.; Valavanis, K.P. Forecasting stock market short-term trends using a neuro-fuzzy based methodology. Expert Syst. Appl. 2009, 36, 10696–10707. [Google Scholar] [CrossRef]
  18. Box, G.; Jenkins, G.; Reinsel, G.; Ljung, G. Time Series Analysis: Forecasting and Control; John Wiley & Sons: Hoboken, NJ, USA, 2015. [Google Scholar]
  19. D’Angelo, G.; Tipaldi, M.; GlieL-Mo, L.; Rampone, S. Spacecraft autonomy modeled via Markov decision process and associative rule-based machine learning. In Proceedings of the 4th IEEE International Workshop on Metrology for AeroSpace, MetroAeroSpace 2017—Proceedings, Padua, Italy, 21–23 June 2017; pp. 324–329. [Google Scholar] [CrossRef]
  20. Roodschild, M.; Gotay Sardiñas, J.; Will, A. A new approach for the vanishing gradient problem on sigmoid activation. Prog. Artif. Intell. 2020, 9, 351–360. [Google Scholar] [CrossRef]
  21. Cui, L.; Yang, S.; Chen, F.; Ming, Z.; Lu, N.; Qin, J. A survey on application of machine learning for Internet of Things. Int. J. Mach. Learn. Cybern. 2018, 9, 1399–1417. [Google Scholar] [CrossRef]
  22. Rong, G.; Mendez, A.; Assi, E.B.; Zhao, B.; Sawan, M. Artificial Intelligence in Healthcare: Review and Prediction Case Studies. Engineering 2020, 6, 291–301. [Google Scholar] [CrossRef]
  23. Tang, Y.; Chau, K.-Y.; Li, W.; Wan, T. Forecasting Economic Recession through Share Price in the Logistics Industry with Artificial Intelligence (AI). Computation 2020, 8, 70. [Google Scholar] [CrossRef]
  24. Manohar, B.; Das, R. Artificial Neural Networks for Prediction of COVID-19 in India by Using Backpropagation. Expert Syst. 2023, 40, e13105. [Google Scholar] [CrossRef]
  25. Marquardt, D.W. An Algorithm for Least-Squares Estimation of Nonlinear Parameters. SIAM J. Appl. Math. 1963, 11, 431–441. [Google Scholar] [CrossRef]
  26. Golovachev, S. Forecasting the U.S. Stock Market via Levenberg-Marquardt and Haken Artificial Neural Networks Using ICA&PCA Pre-processing Techniques. In Pattern Recognition and Machine Intelligence; Springer: Berlin/Heidelberg, Germany, 2011; pp. 460–467. [Google Scholar] [CrossRef]
  27. Manohar, B.; Das, R.; Lakshmi, M.; Prajapati, J.I.; Reddy, K.M. Artificial Neural Network-Based Stock Price Prediction Using Levenberg-Marquardt Algorithm. In Artificial Intelligence Based Solutions for Industrial Applications; CRC Press: Boca Raton, FL, USA, 2024; pp. 315–337. [Google Scholar]
  28. Selvamuthu, D.; Kumar, V.; Mishra, A. Indian Stock Market Prediction Using Artificial Neural Networks on Tick Data. Financ. Innov. 2019, 5, 16. [Google Scholar] [CrossRef]
  29. Goel, H.; Som, B.K. Stock market prediction, COVID-19 pandemic and neural networks: An SCG algorithm application. Bus. Perspect. Res. 2023, 11, 271–287. [Google Scholar] [CrossRef]
  30. Zhou, R.; Wu, D.; Fang, L.; Xu, A.; Lou, X. A Levenberg–Marquardt Backpropagation Neural Network for Predicting Forest Growing Stock Based on the Least-Squares Equation Fitting Parameters. Forests 2018, 9, 757. [Google Scholar] [CrossRef]
  31. Nawi, N.M.; Khan, A.; Rehman, M.Z. CSLM: Levenberg Marquardt based Back Propagation Algorithm Optimized with Cuckoo Search. J. ICT Res. Appl. 2013, 7, 103–116. [Google Scholar] [CrossRef]
  32. Tiwari, A.K.; Jana, R.K.; Das, D.; Roubaud, D. Informational Efficiency of Indian Stock Market: Evidence from High-Frequency Data Using LSTM Model. Phys. A Stat. Mech. Its Appl. 2019, 516, 114–124. [Google Scholar] [CrossRef]
  33. Dey, P.; Hossain, E.; Hossain, M.I.; Chowdhury, M.A.; Alam, M.S.; Hossain, M.S.; Andersson, K. Comparative Analysis of Recurrent Neural Networks in Stock Price Prediction for Different Frequency Domains. Algorithms 2021, 14, 251. [Google Scholar] [CrossRef]
  34. Wei, W.; Wang, J. Stock Price Prediction Based on Information Entropy and Artificial Neural Network. PeerJ Comput. Sci. 2022, 8, e915. [Google Scholar] [CrossRef]
  35. Yao, J.; Tan, C.L. A Case Study on Using Neural Networks to Perform Technical Forecasting of Forex. Neurocomputing 2000, 34, 79–98. [Google Scholar] [CrossRef]
  36. Kara, Y.; Boyacioglu, M.A.; Baykan, Ö.K. Predicting Direction of Stock Price Index Movement Using Artificial Neural Networks and Support Vector Machines: The Sample of the Istanbul Stock Exchange. Expert Syst. Appl. 2011, 38, 5311–5319. [Google Scholar] [CrossRef]
  37. Garrido, D.R.; Lorenzo, M.S. Application of the Sliding Window Method to the Short Range Prediction System for the Correction of Precipitation Forecast Errors. Environ. Sci. Proc. 2022, 19, 53. [Google Scholar] [CrossRef]
  38. Thu, H.G.T.; Thanh, T.N.; Le Quy, T. A Neighborhood Deep Neural Network Model Using Sliding Window for Stock Price Prediction. In Proceedings of the 2021 IEEE International Conference on Big Data and Smart Computing (BigComp), Jeju Island, Republic of Korea, 17–20 January 2021; pp. 69–74. [Google Scholar] [CrossRef]
  39. Wang, J.; Wang, J.; Zhang, Z.; Guo, S. Forecasting Stock Indices with Back Propagation Neural Network. Expert Syst. Appl. 2012, 38, 14346–14355. [Google Scholar] [CrossRef]
  40. Atsalakis, G.S.; Valavanis, K.P. Surveying Stock Market Forecasting Techniques – Part II: Soft Computing Methods. Expert Syst. Appl. 2009, 36, 5932–5941. [Google Scholar] [CrossRef]
  41. Ballings, M.; Van den Poel, D.; Hespeels, N.; Gryp, R. Evaluating Multiple Classifiers for Stock Price Direction Prediction. Expert Syst. Appl. 2015, 42, 7046–7056. [Google Scholar] [CrossRef]
  42. Fischer, T.; Krauss, C. Deep Learning with Long Short-Term Memory Networks for Financial Market Predictions. Eur. J. Oper. Res. 2018, 270, 654–669. [Google Scholar] [CrossRef]
  43. Teixeira, D.M.; Barbosa, R.S. Stock Price Prediction in the Financial Market Using Machine Learning Models. Computation 2025, 13, 3. [Google Scholar] [CrossRef]
  44. Nelson, D.M.; Pereira, A.C.M.; de Oliveira, R.A. Stock Market’s Price Movement Prediction with LSTM Neural Networks. Expert Syst. Appl. 2017, 84, 67–78. [Google Scholar] [CrossRef]
  45. Cao, J.; Li, Z.; Li, J. Financial Time Series Forecasting Model Based on CEEMDAN and GRU. Appl. Soft Comput. 2021, 101, 107049. [Google Scholar] [CrossRef]
Figure 1. ANN architecture with 25 input nodes in input layer, variable number of nodes from h 1 to h 30 in the hidden layer, and two output prediction nodes in the output layer.
Figure 1. ANN architecture with 25 input nodes in input layer, variable number of nodes from h 1 to h 30 in the hidden layer, and two output prediction nodes in the output layer.
Computation 13 00141 g001
Figure 2. Flowchart of the dynamic ANN.
Figure 2. Flowchart of the dynamic ANN.
Computation 13 00141 g002
Figure 3. (a) Traditional k-fold cross validation. (b) Random k-fold cross validation.
Figure 3. (a) Traditional k-fold cross validation. (b) Random k-fold cross validation.
Computation 13 00141 g003
Figure 4. Shifting K-day window size mechanism.
Figure 4. Shifting K-day window size mechanism.
Computation 13 00141 g004
Figure 5. Flowchart of the proposed methodology.
Figure 5. Flowchart of the proposed methodology.
Computation 13 00141 g005
Figure 6. In each window shift, an ANN changes dynamically the number of nodes in the hidden layer and the number of random k-folds to (i) forecast opening and closing prices and (ii) predict the correct trend for the next day.
Figure 6. In each window shift, an ANN changes dynamically the number of nodes in the hidden layer and the number of random k-folds to (i) forecast opening and closing prices and (ii) predict the correct trend for the next day.
Computation 13 00141 g006
Figure 7. Comparison of the predicted next-day trend with the actual next-day trend for (a) AMAZON with K = 60 window size, (b) APPLE with K = 70 window size, and (c) GOOGLE with K = 40 window size.
Figure 7. Comparison of the predicted next-day trend with the actual next-day trend for (a) AMAZON with K = 60 window size, (b) APPLE with K = 70 window size, and (c) GOOGLE with K = 40 window size.
Computation 13 00141 g007
Figure 8. Actual versus predicted forecasting for (a,c,e) opening and (b,d,f) closing price for abovementioned stocks using dynamic ANN with L-M algorithm and K = (a) 60-, (b) 70-, (c) 40-, (d) 60-, (e) 70-, and (f) 40-day sliding window sizes.
Figure 8. Actual versus predicted forecasting for (a,c,e) opening and (b,d,f) closing price for abovementioned stocks using dynamic ANN with L-M algorithm and K = (a) 60-, (b) 70-, (c) 40-, (d) 60-, (e) 70-, and (f) 40-day sliding window sizes.
Computation 13 00141 g008
Figure 9. Plot regression line for (a,c,e) opening and (b,d,f) closing price for abovementioned stocks using dynamic ANN with L-M algorithm and K = (a) 60-, (b) 70-, (c) 40-, (d) 60-, (e) 70-, and (f) 40-day sliding window sizes.
Figure 9. Plot regression line for (a,c,e) opening and (b,d,f) closing price for abovementioned stocks using dynamic ANN with L-M algorithm and K = (a) 60-, (b) 70-, (c) 40-, (d) 60-, (e) 70-, and (f) 40-day sliding window sizes.
Computation 13 00141 g009
Table 1. Performance metrics across different window shifts, number of hidden layer nodes, and number of random folds for APPLE for K = 70 -day window shift.
Table 1. Performance metrics across different window shifts, number of hidden layer nodes, and number of random folds for APPLE for K = 70 -day window shift.
Window
Shift
Nodes in
Hidden Layer
Random
k-Fold
rTrainrValrTestrAllrmseTrainrmseValrmseTestrmseAllmaeTrainmaeValmaeTestmaeAll
1630.98300.87180.50910.94761.17463.07294.12362.10740.92491.53821.83751.1740
2620.96210.82270.83400.94711.87203.36925.52212.82081.02461.72172.09241.4217
32081.00000.90190.70410.98390.00003.15384.47801.96830.05211.56591.87390.8821
42661.00000.92790.78080.97480.00004.44896.19272.74140.03231.86432.32011.0731
52241.00000.96220.17430.98710.00053.89804.65462.19030.05691.75341.88830.9332
61181.00000.97470.53850.99220.00003.02133.83391.75850.00001.51821.78020.8444
722101.00000.96650.81470.98590.00853.05834.14331.85260.08221.52771.75210.8424
8960.99660.94170.64320.98770.87193.13452.88601.71830.79381.50821.55821.0397
9930.99150.90380.88180.98701.53913.16542.21111.93291.09401.48961.29841.1826
102971.00000.94580.77010.98820.04684.33632.89411.90630.17921.79591.45640.8557
11920.99650.97140.51310.98551.05483.23863.58331.96670.91161.53371.66411.1324
12660.99610.97940.68410.98580.98972.63053.76451.85620.86111.44891.69681.0933
13550.99240.97810.73440.98591.21471.90643.12671.67630.98041.24421.61701.1174
14680.99310.96430.75990.97821.19443.10484.04052.10200.96211.63011.62671.1742
151251.00000.97090.65630.98440.00003.13564.07871.85240.00001.61801.82040.8799
162011.00000.84080.52500.98100.02973.47623.62751.81850.14221.73231.73130.8957
172651.00000.89230.49150.94420.02053.20455.27112.21030.11071.57232.11710.9520
Notes: rTrain, rVal, rTest, rAll: Pearson correlation coefficients for training, validation, testing, and combined datasets. Values closer to 1 indicate strong correlation. rmseTrain, rmseVal, rmseTest, rmseAll: root mean squared error for training, validation, testing, and overall datasets. A lower value means better performance. maeTrain, maeVal, maeTest, maeAll: mean absolute error for training, validation, testing, and overall datasets. Another evaluation metric where a lower value indicates a better fit. This table presents the performance of the proposed model for APPLE stock using a 70-day sliding window shift. Each row corresponds to a different configuration of the model, varying by the number of hidden layer nodes, the number of folds by using random k-fold cross-validation, and the window shift index. The metrics include correlation coefficient (r) for training, validation, and overall, along with rmse (root mean squared error) and mae (mean absolute error) values for each model architecture.
Table 2. Performance metrics across different window shifts, number of hidden layer nodes, and number of random folds for GOOGLE for K = 40 -day window shift.
Table 2. Performance metrics across different window shifts, number of hidden layer nodes, and number of random folds for GOOGLE for K = 40 -day window shift.
Window
Shift
Nodes in
Hidden Layer
Random
k-Fold
rTrainrValrTestrAllrmseTrainrmseValrmseTestrmseAllmaeTrainmaeValmaeTestmaeAll
11160.99960.80190.66800.93770.17852.75973.33681.77830.32981.51201.64530.9432
211100.98350.46480.28000.94791.10272.50973.00301.84020.84591.43931.57201.1088
38101.00000.93870.81390.95860.00001.95682.72631.39500.00001.22701.45540.7774
4210.97990.88990.64860.94760.96043.22735.73662.90840.84001.61012.16011.3130
5430.99750.94380.35910.98900.62122.51952.60491.54310.61551.43401.49040.9740
61870.99820.97430.50930.98810.79161.95993.45821.81080.78701.20191.63501.0626
71620.99970.91330.80790.98190.23363.10812.53831.57630.44081.52641.42480.9043
81270.99930.67390.59530.92190.22303.26353.16471.82070.41371.63881.66760.9974
9860.99380.54820.79320.92500.39802.77152.09861.38210.52741.53661.32030.9061
10210.90380.64370.46860.80381.91322.13543.06092.21591.23491.32781.57581.3211
112190.98230.88030.70450.94520.69863.02472.35401.59310.71131.64761.31921.0089
122111.00000.88550.88500.94390.00122.15132.95781.51830.02991.38151.60390.8626
132650.99720.81020.09090.95320.30751.75992.72741.38700.43871.20741.45250.8531
1410100.98990.96790.59210.95560.80481.42604.04721.99010.76561.09061.85841.1100
152211.00000.97210.60710.99160.02891.92881.87481.07240.13941.23051.25650.7146
1621101.00000.96960.46300.98620.01421.92552.22311.19730.09251.22401.38000.7527
172040.98460.74080.77950.93350.89873.31324.35122.37760.83701.71151.87861.2384
189100.98250.92870.75150.94110.94622.67832.54631.66320.83201.45941.35431.0455
198100.9881-0.19810.36530.92220.79783.00652.77821.74960.80601.36021.51501.0596
203011.00000.20570.61860.93880.01982.67102.90981.59680.10301.42351.48140.8302
Notes: rTrain, rVal, rTest, rAll: Pearson correlation coefficients for training, validation, testing, and combined datasets. Values closer to 1 indicate strong correlation. rmseTrain, rmseVal, rmseTest, rmseAll: root mean squared error for training, validation, testing, and overall datasets. A lower value means better performance. maeTrain, maeVal, maeTest, maeAll: mean absolute error for training, validation, testing, and overall datasets. Another evaluation metric where a lower value indicates a better fit. This table presents the performance of the proposed model for GOOGLE stock using a 40-day sliding window shift. Each row corresponds to a different configuration of the model, varying by the number of hidden layer nodes, the number of folds by using random k-fold cross-validation, and the window shift index. The metrics include correlation coefficient (r) for training, validation, testing, and overall, along with rmse (root mean squared error) and mae (mean absolute error) values for each model architecture.
Table 3. Performance metrics across different window shifts, number of hidden layer nodes, and number of random folds for AMAZON with a K = 60 -day window shift.
Table 3. Performance metrics across different window shifts, number of hidden layer nodes, and number of random folds for AMAZON with a K = 60 -day window shift.
Window
Shift
Nodes in
Hidden Layer
Random
k-Fold
rTrainrValrTestrAllrmseTrainrmseValrmseTestrmseAllmaeTrainmaeValmaeTestmaeAll
12321.00000.91550.70700.97080.00014.25283.53392.02720.00131.90301.62350.9177
2670.95070.94250.65500.92202.49382.92559.67834.36041.36321.42062.52131.5879
3290.97700.87130.64120.98432.38464.14387.80813.88071.33561.79962.63601.6458
41571.00000.95390.76800.98830.06586.11016.05533.16880.21672.14912.26071.1654
5210.98740.98720.59240.97303.70133.169810.51285.20201.64381.54742.76061.8344
6650.99920.99550.33660.99440.89232.46596.11462.58900.83601.39372.28031.2254
71551.00000.97980.67950.99390.12714.05093.35891.93220.31831.76101.60640.9171
81941.00000.93840.47420.96330.00015.48086.14003.04100.00842.06882.21741.1193
9870.99350.84590.63430.98961.04323.65863.86422.15570.91031.71601.82771.2081
101531.00000.96780.65760.98550.00013.75425.13272.36130.00011.77932.06051.0068
112641.00000.97290.06270.98640.00013.17014.53132.05560.00061.59011.89970.9169
121040.99020.97590.72440.98061.88372.85533.93032.41661.19191.52371.81891.3439
132381.00000.95170.61450.98390.01344.30552.95161.90480.09521.82981.56280.8866
142371.00000.90680.37470.97930.00034.11473.92752.09290.01461.81871.74770.9283
15750.99160.94300.85400.97751.41694.05336.25703.02791.03571.91032.24641.4041
16650.99440.96020.11820.98641.40333.95954.25632.45731.03591.86861.77711.2969
172191.00000.94430.50800.99120.12293.69503.40381.84970.29641.81731.69130.9472
181560.99950.95070.46490.99000.44743.21093.73191.86040.53511.55121.70020.9649
Notes: rTrain, rVal, rTest, rAll: Pearson correlation coefficients for training, validation, testing, and combined datasets. Values closer to 1 indicate strong correlation. rmseTrain, rmseVal, rmseTest, rmseAll: root mean squared error for training, validation, testing, and overall datasets. A lower value means better performance. maeTrain, maeVal, maeTest, maeAll: mean absolute error for training, validation, testing, and overall datasets. Another evaluation metric where a lower value indicates a better fit. This table presents the performance of the proposed model for AMAZON stock using a 60-day sliding window shift. Each row corresponds to a different configuration of the model, varying by the number of hidden layer nodes, the number of folds by using random k-fold cross-validation, and the window shift index. The metrics include correlation coefficient (r) for training, validation, testing, and overall, along with rmse (root mean squared error) and mae (mean absolute error) values for each model architecture.
Table 4. Accuracy in % of correct predicted pattern trend for next day with analyzing all K-window sizes with the dynamic ANN with L-M algorithm.
Table 4. Accuracy in % of correct predicted pattern trend for next day with analyzing all K-window sizes with the dynamic ANN with L-M algorithm.
K-Window SizeAMAZONGOOGLEAPPLE
3066.6771.9070.00
4060.5073.0070.00
5064.2169.4773.16
6071.1163.8970.00
7069.4272.3375.29
8068.7568.1273.75
Table 5. Rmse and mae value comparison of the proposed model with existing LSTM and GRU models.
Table 5. Rmse and mae value comparison of the proposed model with existing LSTM and GRU models.
StockLSTMGRUProposed Model
rmsemaermsemaermsemae
APPLE7.48496.19976.77985.37192.02821.0291
GOOGLE6.98365.64756.86725.01581.72080.9892
AMAZON8.94986.73509.40866.77412.68801.1843
NOTE: LSTM = Long Short-Term Memory, GRU = Gated Recurrent Unit, rmse = root mean square error, mae = mean absolute error. Lower numbers indicate better performance.
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.

Share and Cite

MDPI and ACS Style

Prajapati, J.I.; Das, R. Sliding Window-Based Randomized K-Fold Dynamic ANN for Next-Day Stock Trend Forecasting. Computation 2025, 13, 141. https://doi.org/10.3390/computation13060141

AMA Style

Prajapati JI, Das R. Sliding Window-Based Randomized K-Fold Dynamic ANN for Next-Day Stock Trend Forecasting. Computation. 2025; 13(6):141. https://doi.org/10.3390/computation13060141

Chicago/Turabian Style

Prajapati, Jaykumar Ishvarbhai, and Raja Das. 2025. "Sliding Window-Based Randomized K-Fold Dynamic ANN for Next-Day Stock Trend Forecasting" Computation 13, no. 6: 141. https://doi.org/10.3390/computation13060141

APA Style

Prajapati, J. I., & Das, R. (2025). Sliding Window-Based Randomized K-Fold Dynamic ANN for Next-Day Stock Trend Forecasting. Computation, 13(6), 141. https://doi.org/10.3390/computation13060141

Note that from the first issue of 2016, this journal uses article numbers instead of page numbers. See further details here.

Article Metrics

Back to TopTop