import numpy as np
import pandas as pd
import plotly.graph_objs as go
import sklearn.metrics as metrics
import sklearn.metrics as sm
from sklearn.metrics import mean_squared_error
from sklearn.metrics import accuracy_score, confusion_matrix
from pandas_datareader import data, wb
from datetime import date
import cufflinks as cf
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout
import math
!/usr/bin/env python
coding: utf-8
In[1]:
import numpy as np import pandas as pd import plotly.graph_objs as go import sklearn.metrics as metrics import sklearn.metrics as sm from sklearn.metrics import mean_squared_error from sklearn.metrics import accuracy_score, confusion_matrix from pandas_datareader import data, wb from datetime import date import cufflinks as cf import yfinance as yf import pandas as pd import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.layers import Dropout import math
In[2]:
start=pd.to_datetime('2013-01-01') end=pd.to_datetime('2018-01-01')
In[3]:
GOLD = data.DataReader('GC=F', 'yahoo', start, end)
In[4]:
GOLD_processed=GOLD.iloc[:, 3:4].values
In[5]:
scaler = MinMaxScaler(feature_range = (0, 1)) GOLD_training_scaled = scaler.fit_transform(GOLD_processed)
In[6]:
x_train = [] y_train = [] for i in range(60, 1250): x_train.append(GOLD_training_scaled[i-60:i, 0]) y_train.append(GOLD_training_scaled[i, 0]) x_train, y_train = np.array(x_train), np.array(y_train)
In[7]:
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
In[8]:
model = Sequential() model.add(LSTM(units=200, return_sequences=True, activation='relu',input_shape=(x_train.shape[1], 1))) model.add(Dropout(0.2))
model.add(LSTM(units=200, return_sequences=True)) model.add(Dropout(0.2))
model.add(LSTM(units=200, return_sequences=True)) model.add(Dropout(0.2))
model.add(LSTM(units=200, return_sequences=False)) model.add(Dropout(0.2))
In[9]:
model.add(Dense(units = 1)) model.compile(optimizer = 'adam', loss = 'mean_squared_error')
In[10]:
model.fit(x_train, y_train, epochs = 100, batch_size = 32)
In[11]:
start=pd.to_datetime('2018-01-01') end=pd.to_datetime('2018-01-8') GOLD2 = data.DataReader('GC=F', 'yahoo', start, end)
In[12]:
GOLD2_processed=GOLD2.iloc[:, 3:4].values
In[13]:
GOLD_total = pd.concat((GOLD['Close'], GOLD2['Close']), axis=0) test_inputs = GOLD_total[len(GOLD_total) - len(GOLD2) - 60:].values test_inputs = test_inputs.reshape(-1,1) test_inputs = scaler.transform(test_inputs)
In[14]:
test_features = [] for i in range(60, 65): test_features.append(test_inputs[i-60:i, 0])
In[15]:
test_features = np.array(test_features) test_features = np.reshape(test_features, (test_features.shape[0], test_features.shape[1], 1))
In[16]:
predictions = model.predict(test_features)
In[17]:
predictions = scaler.inverse_transform(predictions)
In[18]:
plt.figure(figsize=(10,6)) plt.plot(GOLD2_processed, color='blue', label='Actual Gold Stock Price') plt.plot(predictions , color='red', label='Predicted Gold Stock Price') plt.title('Gold Stock Price Prediction') plt.xlabel('Date') plt.ylabel('Gold Stock Price') plt.legend() plt.show()
In[19]:
print("Mean absolute error =", round(sm.mean_absolute_error(GOLD2_processed, predictions), 2)) print("Mean squared error =", round(sm.mean_squared_error(GOLD2_processed, predictions), 2)) print("Median absolute error =", round(sm.median_absolute_error(GOLD2_processed, predictions), 2)) print("Explain variance score =", round(sm.explained_variance_score(GOLD2_processed, predictions), 2)) print("R2 score =", round(sm.r2_score(GOLD2_processed, predictions), 2))
In[20]:
start=pd.to_datetime('2018-01-01') end=pd.to_datetime('2018-02-01') GOLD3 = data.DataReader('GC=F', 'yahoo', start, end)
In[21]:
GOLD3_processed=GOLD3.iloc[:, 3:4].values
In[22]:
GOLD_total = pd.concat((GOLD['Close'], GOLD3['Close']), axis=0)
In[23]:
test_inputs = GOLD_total[len(GOLD_total) - len(GOLD3) - 60:].values
In[24]:
test_inputs = test_inputs.reshape(-1,1) test_inputs = scaler.transform(test_inputs)
In[25]:
test_features = [] for i in range(60, 82): test_features.append(test_inputs[i-60:i, 0])
In[26]:
test_features = np.array(test_features) test_features = np.reshape(test_features, (test_features.shape[0], test_features.shape[1], 1))
In[27]:
predictions = model.predict(test_features) predictions = scaler.inverse_transform(predictions)
In[28]:
plt.figure(figsize=(10,6)) plt.plot(GOLD3_processed, color='blue', label='Actual Gold Stock Price') plt.plot(predictions , color='red', label='Predicted Gold Stock Price') plt.title('Gold Stock Price Prediction') plt.xlabel('Date') plt.ylabel('Gold Stock Price') plt.legend() plt.show()
In[29]:
print("Mean absolute error =", round(sm.mean_absolute_error(GOLD3_processed, predictions), 2)) print("Mean squared error =", round(sm.mean_squared_error(GOLD3_processed, predictions), 2)) print("Median absolute error =", round(sm.median_absolute_error(GOLD3_processed, predictions), 2)) print("Explain variance score =", round(sm.explained_variance_score(GOLD3_processed, predictions), 2)) print("R2 score =", round(sm.r2_score(GOLD3_processed, predictions), 2))
In[ ]: