Stock Price Forecasting Using Machine Learning

Ravindra Elicherla
Geek Culture
Published in
4 min readApr 4, 2021


Stock price forecasting helps in identifying where the stock moves in the next couple of days or weeks or at least shows the trend. The stock price depends on various factors to name a few —

Fundamental factors: Revenue, profits, market share, potential growth prospects of the business

External factors: Pandemics like Corona, Forex rates, Oil prices, Gold prices, Bond yields, Global stock markets

Technical factors: Price action, Volume, Moving averages, MACD (Moving average convergence divergence), RSI (Relative Strength Index), MFI (Money Flow Index), Pivot point, Derivatives Expiry dates, Options Open Interest, Futures prices

With or without these factors,

  1. Stock prices are not random, they do follow some trend based on past history
  2. Human decisions are a combination of emotional and rational and tend to look at past data
  3. Markets are always right. They only punish the wrong decisions
  4. Greediness, blind calls, high-risk appetite, playing safe either can reward or punish the investor depending on the time.

In this article, we will try Prophet from Facebook


I am picking up CDSL (Central Depository Services (India) Limited) stock for this analysis. Data can be downloaded from and click on Historical Data. Considering 2020 March meltdown in the market as a black swan event, I am taking one-year data from 2020 April to 2021 April.

import pandas as pd
cdsl = pd.read_csv(‘/Users/ravindraprasad/01-Elicherla/01-DataScience/CDSLApril.csv’)

Above code is importing pandas and downloading the data. Please use appropriate folder in your code.

CDSL shows below data with headers.

There is a small problem with column names. Lest list down the columns


As you can see below there is a space at the end of the column name

I am changing the column names

df = cdsl.rename(columns = {‘Date ‘: ‘Date’, ‘series ‘: ‘series’, ‘OPEN ‘: ‘Open’ , ‘HIGH ‘: ‘High’, ‘LOW ‘: ‘Low’, ‘PREV. CLOSE ‘: ‘PREV. CLOSE’, ‘ltp ‘: ‘ltp’, ‘close ‘: ‘close’, ‘vwap ‘: ‘vwap’, ‘52W H ‘: ‘52W H’, ‘52W L ‘: ‘52W L’ , ‘VOLUME ‘: ‘VOLUME’, ‘No of trades ‘:’No of trades’ }, inplace = False)

Now all the columns names are changed to same names but without spaces

To use prophet, date is important variable.

cdsl[‘Date ‘]

This does look like a proper date. But when we sort, there is a challenge. As you can see below, it is not correctly sorted. It is because of incorrect date format.

Now let’s change the date format.

df[‘Date’] = pd.to_datetime(df.Date,format=’%d-%b-%Y’)
df.sort_values(by=[‘Date’], inplace=True, ascending=True)

Now the date is sorted out. Let;s plot the data using matplotlib

from matplotlib import pyplot as plt
import numpy as np
x = df[‘Date’]
y = df[‘ltp’]
plt.plot(x, y)

It is now time to prepare data for Prophet. Prophet needs only two variables. We will use Date and ltp (which is Last Traded Price)

dfdata = df[[“Date”,”ltp”]]
dfdata.rename(columns={“Date”:”ds”}, inplace=True)
dfdata.rename(columns={“ltp”:”y”}, inplace=True)

For Prophet, two variables need to be called as “ds” and “y”, which we renamed above. Let’s have a quick look at data before proceeding with forecast

Import prophet and create model with data.

from fbprophet import Prophet
m = Prophet()

Lets forecast for next 300 days.

future = m.make_future_dataframe(periods=300)

forecast = m.predict(future)
dfforecast= forecast[[“ds”, “yhat”, “yhat_lower”, “yhat_upper”]]
pd.set_option(‘display.max_rows’, dfforecast.shape[0]+1)

fig1 = m.plot(forecast)

fig2 = m.plot_components(forecast)

Lets build interactive graph.

from fbprophet.plot import plot_plotly
import plotly.offline as py
fig = plot_plotly(m, forecast) # This returns a plotly Figure

This model predicts that CDSL reaches Rs. 1000 in November 1st week, with a lower side of Rs. 859 and higher side of Rs. 1164. Lets wait and watch!!!

Disclaimer: Stock prices vary based on many factors not just on past data. This article is no means for investment advice and purely for educational purposes. Please speak to your financial advisor for any specific investment advice.



Ravindra Elicherla
Geek Culture

Geek, Painter, Fitness enthusiast, Options Writer and Simple human