<jupyter_start><jupyter_text>NSE-TATAGLOBAL DATASETS  Stock Market Prediction And Forecasting Using Stacked LSTM  LGMVIP Task-2|| Data Science  To build the stock price prediction model, we will use the NSE TATA GLOBAL dataset. This is a dataset of Tata Beverages from Tata Global Beverages Limited, National Stock Exchange of India: Tata Global Dataset  Import Libraries<jupyter_code>import numpy as np 
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import io
import requests 
import datetime<jupyter_output><empty_output><jupyter_text>Import Datasets<jupyter_code>url="https://raw.githubusercontent.com/mwitiderrick/stockprice/master/NSE-TATAGLOBAL.csv"
df=pd.read_csv(url)
df.head()
df1=df.reset_index()['Open']
df1
plt.plot(df1)<jupyter_output><empty_output><jupyter_text>LSTM are sensitive to the scale of the data. so we apply MinMax scaler<jupyter_code>from sklearn.preprocessing import MinMaxScaler
scaler=MinMaxScaler(feature_range=(0,1))
df1=scaler.fit_transform(np.array(df1).reshape(-1,1))
print(df1)<jupyter_output>[[0.6202352 ]
 [0.62226277]
 [0.64436334]
 ...
 [0.16504461]
 [0.15896188]
 [0.16626115]]<jupyter_text>splitting dataset into train and test split<jupyter_code>train_size=int(len(df1)*0.75)
test_size=len(df1)-train_size
train_data,test_data=df1[0:train_size,:],df1[train_size:len(df1),:1]
train_size,test_size
train_data,test_data<jupyter_output><empty_output><jupyter_text>convert an array of values into a dataset matrix<jupyter_code>def create_dataset(dataset, time_step=1):
    train_X, train_Y = [], []
    for i in range(len(dataset)-time_step-1):
        a = dataset[i:(i+time_step), 0]   ###i=0, 0,1,2,3-----99   100 
        train_X.append(a)
        train_Y.append(dataset[i + time_step, 0])
    return numpy.array(train_X), numpy.array(train_Y)<jupyter_output><empty_output><jupyter_text>reshape into X=t,t+1,t+2,t+3 and Y=t+4<jupyter_code>import numpy
time_step = 100
X_train, y_train = create_dataset(train_data, time_step)
X_test, ytest = create_dataset(test_data, time_step)
print(X_train.shape), print(y_train.shape)<jupyter_output>(1425, 100)
(1425,)<jupyter_text>reshape input to be [samples, time steps, features] which is required for LSTM<jupyter_code>X_train =X_train.reshape(X_train.shape[0],X_train.shape[1] , 1)
X_test = X_test.reshape(X_test.shape[0],X_test.shape[1] , 1)<jupyter_output><empty_output><jupyter_text>Create the Stacked LSTM model<jupyter_code>from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import LSTM
model=Sequential()
model.add(LSTM(50,return_sequences=True,input_shape=(100,1)))
model.add(LSTM(50,return_sequences=True))
model.add(LSTM(50))
model.add(Dense(1))
model.compile(loss='mean_squared_error',optimizer='adam')
model.summary()
model.fit(X_train,y_train,validation_data=(X_test,ytest),epochs=100,batch_size=64,verbose=1)
import tensorflow as tf
tf.__version__<jupyter_output><empty_output><jupyter_text>Lets Do the prediction and check performance metrics<jupyter_code>train_predict=model.predict(X_train)
test_predict=model.predict(X_test)
train_predict=scaler.inverse_transform(train_predict)
test_predict=scaler.inverse_transform(test_predict)<jupyter_output><empty_output><jupyter_text>Calculate RMSE performance metrics<jupyter_code>import math
from sklearn.metrics import mean_squared_error
math.sqrt(mean_squared_error(y_train,train_predict))<jupyter_output><empty_output><jupyter_text>Test Data RMSE<jupyter_code>math.sqrt(mean_squared_error(ytest,test_predict))<jupyter_output><empty_output><jupyter_text>shift train predictions for plotting<jupyter_code>look_back=100
trainPredictPlot = numpy.empty_like(df1)
trainPredictPlot[:, :] = np.nan
trainPredictPlot[look_back:len(train_predict)+look_back, :] = train_predict<jupyter_output><empty_output><jupyter_text>shift test predictions for plotting<jupyter_code>testPredictPlot = numpy.empty_like(df1)
testPredictPlot[:, :] = numpy.nan
testPredictPlot[len(train_predict)+(look_back*2)+1:len(df1)-1, :] = test_predict<jupyter_output><empty_output><jupyter_text>plot baseline and predictions<jupyter_code>plt.plot(scaler.inverse_transform(df1),color='blue')
plt.show()
plt.plot(trainPredictPlot,color='red')
plt.show()
plt.plot(testPredictPlot,color='green')
plt.show()
plt.plot(trainPredictPlot,color='red')
plt.plot(testPredictPlot,color='green')
plt.show()
plt.plot(scaler.inverse_transform(df1),color='blue')
plt.plot(trainPredictPlot,color='red')
plt.plot(testPredictPlot,color='green')
plt.show()
len(test_data)
x_input=test_data[341:].reshape(1,-1)
x_input.shape
model.save("saved_model.h5")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12483912483912483, 'fraction_numerical': 0.03131703131703132, 'mean_word_length': 9.597727272727273, 'pattern_counts': {'":': 0, '<': 55, '<?xml version=': 0, '>': 55, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '14', 'dir': 'jupyter-structured-clean-dedup', 'id': '17011', 'license': 'Apache-2.0', 'n_tokens_mistral': 1846, 'n_tokens_neox': 1734, 'n_words': 264, 'path': 'Beginner Level Task/Stock Market Prediction/Stock Market Prediction2.ipynb', 'repo_name': 'ankiii07/LGMVIP-DataScience', 'size': '4662'}