页面简介
Stock market predictions using machine learning and deep learning techniques, such as Moving Averages, knn, ARIMA, prophet, and LSTM.
正文摘录
India's Most Futuristic AI Conference Is Back – Bigger, Sharper, Bolder d : h : m : s Get Details Interview PrepCareerGenAIPrompt EnggChatGPTLLMLangchainRAGAI AgentsMachine LearningDeep LearningGenAI ToolsLLMOpsPythonNLPSQLAIML Projects Reading list IntroductionUnderstanding Time SeriesUnivariate and Multivariate Time Series with Examples Common PatternsStationary and Non Stationary Time SeriesAnalyzing Time Series Data using Python Validation TechniquesRolling Cross Validation Time Series ForecastingWhat is Time Series Forecasting?Machine Learning for Time Series ForecastingFeature Engineering Techniques for Time Series Data Exponential SmoothingSimple Exponential SmoothingHolt Winters AlgorithmTime Series in Dashboards ARIMAIntroduction to ARIMAHow to Check Stationary?Implement ARIMA ProphetProphetImplement Prophet Deep LearningTime Series Forecasting using Deep Learning Stock Market Price Prediction Using Deep Learning Aishwarya Singh Last Updated : 14 Apr, 2025 12 min read Predicting stock market prices is challenging due to countless factors, from economic data to human behavior, making prices volatile and hard to forecast. Deep learning can help by analyzing patterns in historical data, company announcements, and financial reports to uncover insights traditional methods miss. This article explores stock price prediction using machine learning, starting with basic models like averaging and linear regression, then advancing to techniques like Auto ARIMA and LSTM. These methods analyze past trends to improve accuracy, offering a data-driven approach to navigate the complexities of the market without relying on hype or speculation. The core idea behind this article is to showcase how these algorithms are implemented. I will briefly describe the technique and provide relevant links to brush up on the concepts as and when necessary. In case you’re a newcomer to the world of time series, I suggest going through the following articles first: Table of contentsUnderstanding the Problem StatementMoving AverageLinear Regressionk-Nearest NeighboursAuto ARIMAProphetLong Short Term Memory (LSTM)ConclusionFrequently Asked Questions Understanding the Problem Statement We’ll dive into the implementation part of this article soon, but first, it’s important to establish what we aim to solve. Broadly, stock market machine learning analysis is divided into Fundamental Analysis and Technical Analysis. Fundamental Analysis involves analyzing a company’s future profitability based on its current business environment and financial performance. Technical Analysis, on the other hand, includes reading the charts and using statistical figures to identify the trends in the stock market. As you might have guessed, our focus will be on the technical analysis part. We’ll be using a dataset from Quandl (you can find historical data for various stocks here) and for this particular project, I have used the data for ‘Tata Global Beverages’. Time to dive in! Note: Here is the dataset I used for the code: Download We will first load the dataset and define the target variable for the problem: Python Code: #import packages import pandas as pd import numpy as np #for normalizing data from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler(feature_range=(0, 1)) #read the file df = pd.read_csv('NSE-TATAGLOBAL11.csv') df.head() The dataset contains multiple variables: date, open, high, low, last, close, total_trade_quantity, and turnover. The columns Open and Close represent the starting and final price at which the stock is traded on a particular day. High, Low and Last represent the maximum, minimum, and last price of the share for the day. Total Trade Quantity is the number of shares bought or sold in the day and Turnover (Lacs) is the turnover of the particular company on a given date. Another important thing to note is that the market is closed on weekends and public holidays. Notice the above table again; some date values are missing—2/10/2018, 6/10/2018, and 7/10/2018. Of these dates, the 2nd is a national holiday, while the 6th and 7th fall on a weekend. The profit or loss calculation is usually determined by the closing price of a stock for the day, hence we will consider the closing price as the target variable. Let’s plot the target variable to understand how it’s shaping up in our data: #setting index as date df['Date'] = pd.to_datetime(df.Date,format='%Y-%m-%d') df.index = df['Date'] #plot plt.figure(figsize=(16,8)) plt.plot(df['Close'], label='Close Price history') In the upcoming sections, we will explore these variables and use different techniques to predict the stock’s daily closing price. Moving Average ‘Average’ is easily one of the most common things we use in our daily lives. Calculating the average marks to determine overall performance or finding the average temperature of the past few days to get an idea about today’s temperature are all routine tasks we do on a regular basis. So, this is a good starting point to use on our dataset for making predictions. The predicted closing price for each day will be the average of a set of previously observed values. Instead of using the simple average, we will use the moving average technique, which uses the latest set of values for each prediction. In other words, for each subsequent step, the predicted values are taken into consideration while removing the oldest observed value from the set. Here is a simple figure that will help you understand this more clearly. We will implement this technique on our dataset. The first step is to create a dataframe that contains only the Date and Close price columns, then split it into train and validation sets to verify our predictions. Implementation # importing libraries import pandas as pd import numpy as np # reading the data df = pd.read_csv('NSE-TATAGLOBAL11.csv') # looking at the first five rows of the data print(df.head()) print('\n Shape of the data:') print(df.shape) # setting the index as date df['Date'] = pd.to_datetime(df.Date,format='%Y-%m-%d') df.index = df['Date'] #creating dataframe with date and the target variable data = df.sort_index(ascending=True, axis=0) new_data = pd.DataFrame(index=range(0,len(df)),columns=['Date', 'Close']) for i in range(0,len(data)): new_data['Date'][i] = data['Date'][i] new_data['Close'][i] = data['Close'][i] # NOTE: While splitting the data into train and validation set, we cannot use random splitting since that will destroy the time component. So here we have set the last year’s data into validation and the 4 years’ data before that into train set. # splitting into train and validation train = new_data[:987] valid = new_data[987:] # shapes of training set print('\n Shape of training set:') print(train.shape) # shapes of validation set print('\n Shape of validation set:') print(valid.shape) # In the next step, we will create predictions for the validation set and check the RMSE using the actual values. # making predictions preds = [] for i in range(0,valid.shape[0]): a = train['Close'][len(train)-248+i:].sum() + sum(preds) b = a/248 preds.append(b) # checking the results (RMSE value) rms=np.sqrt(np.mean(np.power((np.array(valid['Close'])-preds),2))) print('\n RMSE value on validation set:') print(rms) Just checking the RMSE does not help us understand how the model performed. Let’s visualize this to get a more intuitive understanding. Here is a plot of the predicted values along with the actual values. #plot valid['Predictions'] = 0 valid['Predictions'] = preds plt.plot(train['Close']) plt.plot(valid[['Close', 'Predictions']]) Inference The RMSE value is close to 105, but the results are not very promising (as shown in the plot). The predicted values are of the same range as the observed values in the train set (initially, there is an increasing trend and then a slight decrease). In the next section, we will examine two commonly used machine learning techniques—linear Regression and kNN—and see how they perform on our stock market machine learning data. Linear Regression The most basic machine learning algorithm that can be implemented on this data is linear regression. The linear regression model returns an equation determining the relationship between the independent and dependent variables. The equation for linear regression can be written as: Here, x1, x2,….xn represent the independent variables while the coefficients θ1, θ2, …. θn represent the weights. You can refer to the following article to study linear regression in more detail: A comprehensive beginners guide for Linear, Ridge and Lasso Regression. For our problem statement, we do not have a set of independent variables. Instead, we have only the dates. Let us use the date column to extract features like day, month, year, Monday/Friday, etc., and then fit a linear regression model. Implementation We will first sort the dataset in ascending order and then create a separate dataset so that any new feature created does not affect the original data. #setting index as date values df['Date'] = pd.to_datetime(df.Date,format='%Y-%m-%d') df.index = df['Date'] #sorting data = df.sort_index(ascending=True, axis=0) #creating a separate dataset new_data = pd.DataFrame(index=range(0,len(df)),columns=['Date', 'Close']) for i in range(0,len(data)): new_data['Date'][i] = data['Date'][i] new_data['Close'][i] = data['Close'][i] #create features from fastai.structured import add_datepart add_datepart(new_data, 'Date') new_data.drop('Elapsed', axis=1, inplace=True) #elapsed will be the time stamp This creates features such as: ‘Year’, ‘Month’, ‘Week’, ‘Day’, ‘Dayofweek’, ‘Dayofyear’, ‘Is_month_end’, ‘Is_month_start’, ‘Is_quarter_end’, ‘Is_quarter_start’, ‘Is_year_end’, and ‘Is_year_start’. Note: I have used add_datepart from the fastai library. If you do not have it installed, you can simply use the command pip install fastai. Otherwise, you can create these features using simple for loops in Python. I have shown an example below. Apart from this,