Now Reading
Time Series Forecasting On NSE Of India Using Facebook’s NeuralProphet

Time Series Forecasting On NSE Of India Using Facebook’s NeuralProphet

Predicting stock prices can be difficult as it involves various factors. Both the government and companies keep changing their policies and strategies which affect stocks massively to either rise or fall anytime. The stock market is the most unpredictable area as these factors are unforeseen and subject to change in future. Thus it is difficult to make models that can accurately predict stock prices. However, it is possible to predict the trends, seasonality and other parameters based on the previous historical data. With the advent of deep learning state of the art models, many systems are adapting it. 

NeuralProphet

Last week Facebook released its new open source time series modelling Python library NeuralProphet, a PyTorch based neural network forecasting tool. Neural Prophet is an up-gradation to Facebook’s previously launched Prophet library. It is also based on AR-Net. The NeuralProphet framework addresses some key points – customization, scalability and extensibility. It is built on top of statistical and neural network models for time series modelling, used in any kind of forecasting and anomaly detection. NeuralProphet was created in collaboration with researchers at Monash and Stanford University. It’s easy-to-use and enables researchers and engineers to build better time-based data models

NeuralProphet consists of components like trends, multiple seasonality modelled using Fourier terms, auto-regression implemented using Auto-Regressive Feed-Forward Neural Network, special events, future regressors and lagged regressors. 

Dataset

Established in 1992, National Stock Market of India or NSE is the first dematerialized electronic stock exchange market located in Mumbai, India. NSE holds a record listing of 1952 stocks with a market capitalization of $2.7 trillion (as of 2018) and volume of $400 billion (as of June 2014). NSE brought about transparency to the Indian equity markets by allowing everyone eligible (as per requirements set by NSE) to trade instead of just a group of brokers. This changed the whole trading scenario in Indian Stock price information which was earlier only accessed by the registered members then became open to all clients even at a remote location. This took the form of electronic deposit accounts, and balances were maintained on time. 

The data is the price history and trading volumes of the 52 stocks in the index NIFTY 50 from NSE India. All dataset has day-day pricing and trading values present across CSV files. Each of these stocks contains a metadata file and macro-information within it. The data is collected from 1st January 2000 to 30th October 2020.

Dataset can be downloaded from here.

There are 15 parameters:

Date, Symbol(Name of the Stock), Series, Prev Close(Previous day Closing price), Open(the opening price of that day), High(the maximum price of the day), Low( the least price for that day), Close( closing price for the day), VWAP(the average price security traded for that day, based on both volume and price), Volume, Turnover, Trades, Deliverable Volume, %Deliverable.

Stock Price Forecasting Using NeuralProphet

Installation: The GitHub repository can be cloned and used otherwise using pip.

pip install neuralprophet 

or 

pip install neutralprophet[live] – This enables plot_live_live parameter in the train function to get live training and validation plots.

# importing libraries

 import pandas as pd
 import matplotlib.pyplot as plt
 %matplotlib inline
 from neuralprophet import NeuralProphet 

# reading dataset

For demonstration purposes, we will be showing the forecasting on Coal India stocks. Similarly, it can be done on other stocks as well.

 df = pd.read_csv("../input/nifty50-stock-market-data/COALINDIA.csv", parse_dates=["Date"])
 df.head() 

df.tail()

# pattern for neuralprophet 

This is same as Prophet where only two columns are expected ‘ds’ which is the timestamp and ‘y’ the dependent variable( for stocks it is VWAP or Volume Weighted Average Price) 

 df = df[["Date", "VWAP"]]
 df.rename(columns={"Date": "ds", "VWAP": "y"}, inplace=True) 

# defining the model and fitting it

See Also
Facebook Decides To Introduce News Summarisation Tool, What Could Go Wrong

The complete hyperparameter for the model list can be viewed from here. Here ‘D’ stands for calendar day frequency.

 model = NeuralProphet()
 metrics = model.fit(df, validate_each_epoch=True, freq="D") 

# making future predictions from the model.

 future = model.make_future_dataframe(df, periods=365, n_historic_predictions=len(df))
 forecast = model.predict(future) 
 INFO: nprophet - _lr_range_test: learning rate range test found optimal lr: 3.51E-01
 Epoch[40/40]: 100%|██████████| 40/40 [00:05<00:00,  6.81it/s, SmoothL1Loss=0.00905, MAE=18.9, RegLoss=0, MAE_val=51.6, SmoothL1Loss_val=0.0649] 

# plotting the prediction

 fig, ax = plt.subplots(figsize=(14, 10))
 model.plot(forecast, xlabel="Date", ylabel="VWAP", ax=ax)
 ax.xaxis.label.set_size(28)
 ax.yaxis.label.set_size(28)
 ax.tick_params(axis='both', which='major', labelsize=24)
 ax.set_title("Coal India Stocks", fontsize=28, fontweight="bold") 

# plotting the parameters

This shows the trend, trend rate, weekly seasonality and a yearly seasonality.

fig_param = model.plot_parameters()

# plotting loss

 fig, ax = plt.subplots(figsize=(14, 10))
 ax.plot(metrics["MAE"], '-b', linewidth=6, label="Training Loss")  
 ax.plot(metrics["MAE_val"], '-r', linewidth=2, label="Validation Loss")
 ax.legend(loc='center right', fontsize=16)
 ax.tick_params(axis='both', which='major', labelsize=20)
 ax.set_xlabel("Epoch", fontsize=28, fontweight="bold")
 ax.set_ylabel("Loss", fontsize=28, fontweight="bold")
 ax.set_title("Model Loss (MAE)", fontsize=28, fontweight="bold") 

The complete notebook can be accessed from here.

End Notes

In this article, we have implemented time series forecasting over the National Stock Exchange India Nifty 50 index dataset using Facebook’s NeuralProphet library to show the seasonality and trends over time.

What Do You Think?

Join Our Telegram Group. Be part of an engaging online community. Join Here.

Subscribe to our Newsletter

Get the latest updates and relevant offers by sharing your email.

Copyright Analytics India Magazine Pvt Ltd

Scroll To Top