from keras.optimizers import Adam
import matplotlib.pyplot as plt
from keras.models import *
from keras.layers import *
import os
from keras.callbacks import ModelCheckpoint
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"  #
os.environ['CUDA_VISIBLE_DEVICES'] = '0'  # -1 !!!!
import pandas as pd
import numpy as np
def getData_nex(filename):
    data = pd.read_csv(filename, header=0,index_col='Date',
                       names=['Date', 'Open', 'High', 'Volume', 'Close'])#mid of days open High and volumes solds, but the closing is at the end of the day
    Open = data.Open
    High = data.High
    Volume = data.Volume
    Close = data.Close
    DATA = np.column_stack((Open, High, Volume, Close))
    data=DATA
    X = data[:, 0:3]
    Y = data[:, 3]
    xtrain = X[0:-100, 0:3]
    ytrain = np.asarray(Y[0:-100])
    xtest = X[-100:, 0:3]
    ytest = np.asarray(Y[-100:])
    X_train = np.reshape(xtrain, (xtrain.shape[0], xtrain.shape[1],1))
    print (X_train.shape)
    X_test = np.reshape(xtest, (xtest.shape[0],xtest.shape[1],1))
    return X_train,X_test,ytrain,ytest

np.random.seed(1234)
filename='/home/ajay/Videos/stocks_video/Stockdata.csv'
# --------------------------------------------------------------------------
[X_train, X_test, ytrain, ytest] = getData_nex(filename)
input_tensor = Input((3, 1,))#open high and volume as input
x = input_tensor
rnn_size = 128
W_INIT = 'he_normal'
for i in range(3):
    x = GRU(32*2**i,return_sequences=True,
                          go_backwards=True, init=W_INIT)(x)
x=Dropout(0.25)(x)
x=Flatten()(x)
x = Dense(1, activation='linear',kernel_initializer='normal')(x)
model = Model(input=input_tensor, output=x)
adam= Adam(lr=0.0001)
model.compile(loss='mse',
              optimizer='adam')
from keras.utils.vis_utils import plot_model as plot
from IPython.display import Image
plot(model, to_file="mBdel.png", show_shapes=True)
Image('mBdel.png')
plt.show()
checkpoint_callback = ModelCheckpoint('/home/ajay/Videos/stocks_video/check/stocks_pretrained.hdf5'
                                      , monitor='val_loss', verbose=0, save_best_only=True,
                                      save_weights_only=False, mode='auto', period=1)
model.fit(
    X_train, ytrain,
    batch_size=20, nb_epoch=20,verbose=1,
    validation_data=(X_test,ytest),initial_epoch = 0,
    callbacks=[checkpoint_callback]
)


