I wanted to predict stock price in the next 60 days but after I finished writing the code, it predicted backward instead. Can anyone advise me? How can I do it? I revised my code but it’s not working.
My code is
import math
from mplfinance.original_flavor import candlestick_ohlc
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
from sklearn.metrics import mean_squared_error
Tencent2.head()
#Define the features and target
##features = ['Open', 'Vol.']
##target = 'Price'
#Plot line chart
Tencent2['Date'] = pd.to_datetime(Tencent2['Date'])
plt.figure(figsize=(15,6))
plt.plot(Tencent2['Date'], Tencent2['Close'], marker='.')
plt.title('Close by Month', fontsize=15)
plt.xlabel('Date', fontsize=13)
plt.ylabel('Close', fontsize=13)
plt.xticks(rotation=45)
plt.show()
#Plot Candle Chart
matplotlib_date = mdates.date2num(Tencent2['Date'])
ohlc = np.vstack((matplotlib_date,Tencent2['Open'],Tencent2['High'],Tencent2['Low'],Tencent2['Close'])).T
plt.figure(figsize=(15,6))
ax = plt.subplot()
candlestick_ohlc(ax,ohlc,width=0.8,colorup='g',colordown='r')
ax.xaxis_date()
plt.title('Movement of Close Price')
plt.xlabel('Date')
plt.ylabel('Close Price')
plt.xticks(rotation=45)
plt.grid(True)
plt.show()
#Resetting the index
Tencent2.set_index('Date', inplace=True)
#Create a new dataframe with only the 'Close' column
data = Tencent2.filter(['Close'])
#Convert the dataframe to a numpy array
dataset = data.values
#Get the number of rows to train the model on
training_data = math.ceil( len(dataset) * 0.7 )
#Scale the data
scaler = MinMaxScaler(feature_range=(0,1))
scaled_data = scaler.fit_transform(dataset)
#Create the training data set
#Create the scaled training data set
train_data = scaled_data[0:training_data, :]
#Split the data into x_train and y_train data sets
x_train = []
y_train = []
#We create a loop
for i in range(60, len(train_data)):
x_train.append(train_data[i-60:i, 0])
y_train.append(train_data[i, 0])
if i <= 60:
print(x_train)
print(y_train)
print()
#Convert the x_train and y_train to numpy arrays
x_train, y_train = np.array(x_train), np.array(y_train)
#Reshape the data
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
x_train.shape
#Build the LSTM model
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(x_train.shape[1], 1)))
model.add(LSTM(50, return_sequences=False))
model.add(Dense(25))
model.add(Dense(1))
#Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')
#Train the model
model.fit(x_train, y_train, batch_size=1, epochs=1)
#Create the testing data set
#Create a new array containing scaled values from index 1738 to 2247
test_data = scaled_data[training_data - 60:]
#Create the data set X_test and y_test
X_test = []
y_test = dataset[training_data:, :]
for i in range(60, len(test_data)):
X_test.append(test_data[i-60:i, 0])
#Convert the data to a numpy array
X_test = np.array(X_test)
#Reshape the data
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
#Get the model's predicted price values for the X_test data set
predictions = model.predict(X_test)
predictions = scaler.inverse_transform(predictions)
#Evaluate model (get the root mean quared error (RMSE))
rmse = np.sqrt( np.mean( predictions - y_test )**2 )
#Plot the data
train = data[:training_data]
valid = data[training_data:]
valid['Predictions'] = predictions
#Visualize the data
plt.figure(figsize=(16,8))
plt.title('Model')
plt.xlabel('Date', fontsize=18)
plt.ylabel('Close Price', fontsize=18)
plt.plot(train['Close'])
plt.plot(valid[['Close', 'Predictions']])
plt.legend(['Train', 'Validation', 'Predictions'], loc='lower right')
plt.show()
I want to predict the price 60 days into the future, but the price is predicted in the past. Thank you for your help.