Research on HMM-Based Efficient Stock Price Prediction

. Stock market is one of the most important parts of the investment market. Compared with other industries, the stock market not only has a higher rate of return on investment but also has a higher risk, and stock price prediction has always been a close concern of investors. Therefore, the research on stock price prediction methods and how to reduce the error of stock price prediction has become a hot topic for many scholars at home and abroad. In recent years, the development of computer technology such as machine learning and econometric method makes the stock price prediction more reliable. Due to the hidden Markov nature of stock price, this paper proposes a stock price prediction method based on hidden Markov model (HMM). To be speciﬁc, since the data of stock price have continuity in time series, it is necessary to extend the discrete HMM to the continuous HMM, and then put forward the up and down trend prediction model based on the continuous HMM. The ﬁrst-order continuous HMM is extended to the second-order continuous HMM, and the stock price is predicted by combining the prediction method of ﬂuctuation range. As a result, the proposed second-order continuous HMM-based stock price prediction model is simulated on Hang Seng Index (HSI), one of the earliest stock market indexes in Hong Kong. The evaluation results on six months HSI show that the predicted value of the proposed model is very close to the actual value and outperforms three benchmarks in terms of RMSE, MAE, and R 2 .


Introduction
In recent years, with the increasing number of listed companies, stock has become one of the hot topics in the financial field [1]. On the one hand, the trend of stock price will determine the trend of many economic behaviors to a certain extent, so the stock price prediction is also concerned by more and more financial investors and financial analysts [2,3]. On the other hand, as the number of investors in the stock market increases year by year, only by accurately analyzing the future trend of stock prices can quickly grasp the market trend and obtain more investment returns. Stock price prediction is the focus of financial research, which is generally considered as a challenging task because of great instability of financial markets [4]. However, in order to obtain profits or understand the nature of the stock market, many market participants or researchers try to use various methods to predict stock prices [5]. e stock market trades with high frequency every day, thus generating a large amount of stock related data [6]. However, as a matter of fact, such huge amount of data are metaphysical for investors. How to extract valuable information from massive stock data with effective methods has become a problem to be solved at present. However, Brealey's "Fundamentals of Corporate Finance" mentions that the price trend of stocks is unpredictable [7]. At present, the mainstream view of the academic community is that predicting stock price is equivalent to predict the return rate of stock. Return rate of stock is predictable, which is not inconsistent with the efficient markets hypothesis [8,9]. In fact, any variable with a nonzero correlation can predict returns [10]. e efficient market hypothesis is equivalent to the fact that the stock price has fully reflected all the known information, so any information that affects the price can predict the return rate of the stock.
In the traditional quantitative investment field, the selection of target stocks and the prediction of stock prices are mostly based on the results of long-term stock market experience [11]. e antirisk ability and long-term prediction ability of empirical stock analysis methods are often poor, and it is not easy to spread and promote [12]. In addition, the analysis speed of traditional method is often slow. en came the stock analysis methods based on statistics and finance, which is also the beginning of mathematical modeling of stocks, such as autoregressive model [13], stochastic volatility model [14], and Markov model [15]. e prediction and analysis effect of these methods is better than empirical methods. Moreover, due to the use of mathematical modeling, these models are very suitable for computer analysis, which are based on a small amount of input data, and cannot be applied to the current large-scale data scenario.
anks to the continuous development of computer technology and the Internet, it is possible for artificial intelligence to enter the field of financial analysis. Since the stock price is an observable time series, the factors that determine the stock price belong to unknown variables [16].
is feature is consistent with hidden Markov model (HMM), which has been applied to stock price prediction by many scholars [17]. HMM is a statistical model that has been used in automatic speech recognition [18], DNA sequence analysis [19], image processing [20], and pattern recognition [21]. e main contribution of this paper is that the secondorder continuous HMM-based model is constructed for stock price prediction. e rest of this paper is organized as follows. Section 2 reviews related work. In Section 3, HMM-based stock price prediction model is presented. Experimental results are presented in Section 4. Section 5 concludes this paper and gives future work.

Related Work
Nowadays, stock price prediction has made a lot of achievements and related technologies are becoming more and more mature. Especially since the introduction of artificial intelligence related methods, stock price prediction methods have made great progress. In addition, due to the theoretical development of the financial field, the mathematical models used to describe the stock are also more abundant. At present, the research on stock price prediction can be divided into two directions: statistics-based and nonstatistical. For the stock price prediction method based on statistics, in [22], a news augmented generalized autoregressive conditional heterscedasticity (NA-GARCH) model was proposed to use quantitative news sentiment and its impact on asset price movement as the second information source to predict the fluctuation of asset price return together with asset time series data. In [23], the authors introduced deep learning method into the study of stock market correlation. Based on recurrent deep neural network and GARCH model, a hybrid model was proposed for stock price prediction. In [24], geometric Brownian motion mathematical model was used to predict the future price of stock. In [25], optimized custom moving average most suitable for stock time series smoothing was proposed to smooth stock price series and forecast trend direction. In [26], the authors used the exponential smoothing method to process the initial data, calculate the relevant technical indicators as the characteristics to be selected, and optimize the random forest to predict the stock trend. In [27], the authors proposed a hybrid extreme gradient boosting framework and auto regressive integrated moving average model to predict stock price. In [28], a combined predicting method based on wavelet multiresolution analysis was proposed to predict the stock market more accurately and concisely. In [29], a prediction method of stock price volatility based on time series analysis technology was proposed.
For stock price prediction methods based on nonstatistics in [30], a convolutional neural networks-bi-directional long short-term memory-attention mechanism (CNN-BiLSTM-AM) method was proposed to predict the stock closing price of the next day. In [31], a new method of predicting stock trend based on graph convolution neural network model was proposed, which considered both stock market information and individual stock information. In [32], a model called feature fusion long-term and short-term memory convolution neural network was proposed to predict stock prices. In [33], a convolution neural network model based on deep decomposition machine and attention mechanism was constructed to improve the prediction accuracy of stock price movement. In [34], a stock price predicting method integrating multiple data sources and investor sentiment was proposed. In [35], a prediction method of stock market price trend based on high order HMM was presented. In [36], a multisource heterogeneous data analysis method was constructed to integrate multisource information, namely transaction data, news event data, and investor comments to predict future stock price. In [37], an adaptive hidden Markov abnormal state model (AHMMAS) was proposed to model and detect price manipulation activities.

HMM-Based Stock Price Prediction
3.1. HMM Introduction. HMM is usually characterized by the following five elements.
(i) N, number of hidden states in model. Record each state as S � s 1 , s 2 , · · · s t · · · , s N , and s t represents the state at time t. represents the probability that the state at time t + 1 is s i when the known state is s j at time t.
, observation probability matrix when hidden state is j, which represents the probability that the observed value is o k when the state is s j at time t. (v) Π � π i , initial state probability distribution, which represents the probability that the hidden state is s j at the initial time t � 1.
A complete HMM includes state transition probability matrix, observation probability matrix, and initial probability distribution. For simplicity, a simple notation can be used to represent the complete parameters of HMM. (1)

Second-Order Continuous HMM.
In the first-order HMM, the state of the current moment is assumed to be only related to the state of the previous moment and has no relationship with the state of other moments, namely the socalled first-order hidden Markov property. It is obvious that such assumption has certain defects, so it is necessary to establish the second-order HMM to make up for its defects, and the second-order HMM can overcome many shortcomings of the first-order HMM. On this basis, this paper extends the first-order HMM to the second-order HMM for efficient stock price prediction. e closing prices from July 31, 2021 to December 31, 2021, were selected as the research subjects. e Gaussian mixture model can be used to extend the discrete HMM to the continuous HMM. e HMM also has shortcomings in model assumptions, that is, there are many factors affecting the stock price. e stock price of the day cannot be affected only by the stock price of the previous day, which is very unreasonable for the prediction of the stock price. erefore, in order to improve the model, the first-order HMM is extended to the second-order HMM, so as to generate the final model, that is, the second-order continuous HMM, which also strengthens the model foundation for the prediction of stock price index.
In order to explain the Baum-Welch algorithm [38] of the second-order continuous HMM, the Baum-Welch algorithm of the first-order continuous HMM can be referred. erefore, a custom variable [39] δ t (m, n, u) is also be used, which represents the probability that the model is in state s m at time t − 1, state s n at time t, and state s u at time t + 1 under the condition of given Λ and O, that is δ t (m, n, u) � P q t−1 � s m , q t � s n , q t+1 � s u |O, Λ . (2) Define another custom variable δ t (m, n), which represents the probability that the model is in state s m at time t − 1, state s at time t under the condition of given Λ and O, that is and we have where τ t (m, n) is the probability of the mth mixed component of the observation vector O t at time t, that is Because the mixture Gaussian density function is selected, the parameter estimation problem is transformed from the parameter estimation of the observed probability matrix B 2 to the estimation of parameter W m,n , φ m,n , m, n, and the parameter estimation is as follows:

Stock Price Prediction Model.
is section proposes a new prediction method based on the continuous HMM Baum-Welch algorithm combined with K-means clustering and dichotomy to classify data, and the specific steps are as follows: Step 1. For closing prices series CP t , t � 1, 2, · · · , T in one day, let Y t � CP t+1 − CP t /CP t , t � 1, 2, · · · , T-1. According to the generated observation series Y t , a moderate initial growing rate α 0 is determined, and α 0 � max(Y t ) + min(Y t )/2.
Step 2. Hidden states can be divided into small growing rate g 1 (less than α 0 ) and large growing rate g 2 (larger than α). When Y t < α 0 , hidden state is in small growing state g 1 at time t, that is, I t � 1, else I t � 2. erefore, the certain initial state probability distribution Π and state transition matrix A cab be calculated.
Step 3. According to the index series I t , the closing prices series CP t is divided into two types of data, and a reasonable number of mixed components M is determined. K-means clustering is performed on both two types of data, and the initial parameter W m,n , φ m,n and m, n are determined, so the initial continuous HMM is determined.
Step 4. Determine the convergence threshold and carry out multiple iterations according to Baum-Welch algorithm of the continuous HMM until the model enters the convergence saturation state, the output log likelihood tends to be stable, and finally the convergence threshold is determined.
Step 5. Decode the model to obtain the hidden state at time t. If hidden state is the small growing state g 1 , then a n+1 � a n + min(Y t )/2, max(Y t ) � a n , and repeat Step 2 to Step 5, if hidden state is in the large growing state g 2 , then Mobile Information Systems a n+1 � a n + max(Y t )/2, min(Y t ) � a n , and repeat Step 2 to Step 5. is loop continues until the initial state probability distribution Π does not change, and the final growing state α F is obtained.
Step 6. e predicted data at time t + 1 are as follows.

Experimental Setup.
For most stocks, because each stock has its own trend, it cannot well measure the local stock market, and Hang Seng Index (HSI) is one of the earliest stock market indexes in Hong Kong, which can better reflect the price movements of major industry sectors of the market. e closing prices from July 1, 2021 to December 31, 2021, were selected as the research subjects. As of December 31, 2021, all information for an index prior to its launch date is back-tested, and back-tested performance reflects hypothetical historical performance. e data should be preprocessed before the prediction. We convert the daily closing price sequence of stocks into the corresponding benefit sequence. Due to the complexity of stock market, normal distribution cannot accurately simulate the probability distribution of observed values. erefore, the probability of the observed value generated by the HMM model is transformed into the probability of each discrete value by discretizing the stock return rate. e rolling prediction method was used to make 1-month prediction, 3-month prediction, and 6-month prediction. To verify the effectiveness of the algorithm proposed in this paper, NA-GARCH [22], CNN-BiLSTM-AM [30], and AHMMAS [37] were used for the comparison. In order to evaluate the performance of the proposed algorithm on stock price prediction, this paper uses three regression evaluation metrics: root mean square error (RMSE), mean absolute error (MAE), and R 2 to quantify the performance of the model. e three metrics are calculated as follows: where CP i is the actual value, CP i ' is the predicted value, CP i is the mean value of the actual value, and N is the number of samples. RMSE and MAE are used to measure the deviation between the actual value and the predicted value. e smaller the value is, the closer the predicted value is to the actual value. R 2 is used to measure the fitting degree of model, and the closer it is to 1, the better fitting the model is.

Experimental Results.
As can be seen from Figure 1, the predicted values and actual values of the four algorithms are similar in some places, but there is a big difference in some places, and even the opposite trend appears in some places. On the whole, the volatility is large. e volatility of the proposed algorithm is small, especially on some dates, which is basically consistent with the actual value. In contrast, the other three baselines did not perform well in some aspects, especially when the stock market was volatile, which was quite different from the actual value. It can be seen from Figure 2 that the overall trend of the broken line is very similar from the comparison of the predicted value with the actual value over the 3 months, except for the opposite fluctuations at certain time, but the overall effect is better. It is still obvious that the curve between the predicted value and the actual value of the algorithm in this paper is the closest. e error between the predicted result and the actual value of the model is small and the fitting degree is high. AHMMAS algorithm and CNN-BiLSTM-AM algorithm have a large error between the predicted value and the true value on HSI, and the fitting degree of the predicted value curve and the actual value curve is low. e error between the predicted value and the actual value of NA-GARCH algorithm on HSI is the largest.
As indicated in Figure 3, in the comparison between the predicted value and the actual value in 6 months, the overall effect is not very ideal. By comparing the prediction accuracy between the predicted value and the actual value of each algorithm, it can be found that the prediction accuracy of NA-GARCH is the lowest, the prediction accuracy of CNN-BiLSTM-AM is higher than NA-GARCH, and the prediction accuracy of AHMMAS is significantly higher than CNN-BiLSTM-AM. erefore, we can see the efficiency and stability of the proposed algorithm. e Gaussian mixture model can be used to extend the discrete HMM to the continuous HMM.
e HMM also has shortcomings in model assumptions, that is, there are many factors affecting the stock price. e stock price of the day cannot be affected only by the stock price of the previous day, which is very unreasonable for the prediction of the stock price. erefore, in order to improve the model, the first-order HMM is extended to the second-order HMM, so as to generate the final model, that is, the second-order continuous HMM, which also strengthens the model foundation for the prediction of stock price index.
In order to eliminate the result contingency caused by one experiment, 10 experiments were performed on each model, and the average value of multiple results was taken to obtain the final experimental results, as shown in  It can be seen from Figures 4-6 that RMSE and MAE obtained by the algorithm in this paper on three data sets are both smaller than those of other models, and R 2 is closer to 1, indicating that compared with other models, the stock price predicted by the algorithm in this paper is closer to the actual value and the model fits better. It is proved that the secondorder continuous HMM can effectively improve the performance of stock price prediction. Among them, the prediction error of AHMMAS model is smaller than that of NA-       GARCH model and CNN-BilSTM-AM model. is is because AHMMAS extracts more effective features from the original data, so the prediction error is smaller.

Conclusion and Future Work
Since the stock price data have a certain Markov property in time series, at first, based on the relevant properties of hidden Markov model, this paper proposes a new efficient stock price prediction method based on HMM. en, in order to solve the continuity problem of stock price index and the deficiency of model assumption, this paper extends discrete HMM to continuous HMM and extends the firstorder continuous HMM to multiorder continuous HMM by deriving Baum-Welch algorithm. e second-order continuous HMM is used to predict the up and down trend of stock price. Finally, combined with K-means clustering algorithm and dichotomy, the stock price is successfully predicted.
e evaluation results demonstrate that the proposed model is more efficient than three benchmarks.
In this paper, how to choose the initial value of HMM is not discussed, but the selection of initial value often has a great influence on the model. (1) Whether the initial value obtained according to a specific algorithm can improve the accuracy and efficiency of the model prediction in this paper remains to be further discussed. (2) is paper mainly predicts the market state and price, but it does not explain how to process empirical results and how to make investment. (3) is paper only studies the accuracy of model prediction for HSI. Without targeting individual stocks or other indexes, the adaptability of the model cannot be proved.

Data Availability
All data used to support the findings of the study are included within this paper. Mobile Information Systems 7