import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

#importing the dataset
dataset_train = pd.read_csv('Google_Stock_Price_Train.csv')
training_set=dataset_train.iloc[:,1:2].values

#feature scaling
""" we use the formulae
  x_norm=(x-min(x))/max(x)-min(x) """
from sklearn.preprocessing import MinMaxScaler
sc=MinMaxScaler(feature_range=(0,1))
training_set_scaled=sc.fit_transform(training_set) 

#creating a dataset with 60 timesteps and 1 output
X_train=[]
Y_train=[]
for i in range(60,1258):
    X_train.append(training_set_scaled[i-60:i,0])
    Y_train.append(training_set_scaled[i,0])
X_train,Y_train=np.array(X_train),np.array(Y_train)    

#reshaping
X_train=np.reshape(X_train, (X_train.shape[0],X_train.shape[1],1))

#Building the RNN
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import LSTM

#initialising the RNN
regressor=Sequential()

#Adding the first LSTM layer and some Dropout regularisation
regressor.add(LSTM(units=50,return_sequences= True,input_shape=(X_train.shape[1],1)))
regressor.add(Dropout(0.2))

#Adding the second LSTM layer and some dropout regularisation
regressor.add(LSTM(units=50,return_sequences= True))
regressor.add(Dropout(0.2))

#Adding the third LSTM layer and some dropout regularisation
regressor.add(LSTM(units=50,return_sequences= True))
regressor.add(Dropout(0.2))

#Adding the fourth LSTM layer with some dropout
regressor.add(LSTM(units=50,return_sequences= False))
regressor.add(Dropout(0.2))

#Adding the output layer
regressor.add(Dense(units=1))

#Compile the RNN
regressor.compile(optimizer='adam',loss='mean_squared_error')

#Fitting the RNN to the training set
regressor.fit(X_train,Y_train,epochs=100, batch_size=32)

#Making the predictions and visualising the results

#getting the real stock price of 2017
dataset_test = pd.read_csv('Google_Stock_Price_Test.csv')
real_stock_price =dataset_test.iloc[:,1:2].values

#Getting the predicted stock price of 2017
#concatinating the original training and test set
dataset_total =pd.concat((dataset_train['Open'],dataset_test['Open']),axis=0) #Vertical concatinating of open stock prices
inputs=dataset_total[len(dataset_total)-len(dataset_test)-60:].values
inputs=inputs.reshape(-1,1)
inputs=sc.transform(inputs)
X_test=[]
for i in range(60,80):
    X_test.append(inputs[i-60:i,0])
X_test=np.array(X_test)   
X_test=np.reshape(X_test, (X_test.shape[0],X_test.shape[1],1))
predicted_stock_price=regressor.predict(X_test)
predicted_stock_price=sc.inverse_transform(predicted_stock_price)


#visualising the results
plt.plot(real_stock_price,color='red',label='Real google stock price')
plt.plot(predicted_stock_price,color='blue',label='predicted google stock price')
plt.title('Google stock price prediction')
plt.xlabel('Time')
plt.ylabel('Stock prices')
plt.legend()
plt.show()

































