Use this model and make a prediction for the next day (This model is trained on the data…
- User
Use this model and make a prediction for the next day (This model is trained on the data start='2009-01-01', end='2021-01-01' now give a prediction for what will be the price on 2021-01-02 (I have no information of that day)):
import yfinance as yf import pandas as pd import numpy as np from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import Dense, LSTM from keras.callbacks import LambdaCallback import datetime import matplotlib.pyplot as plt import matplotlib.dates as mdates
nifty = yf.download('^NSEI', start='2009-01-01', end='2021-01-01')
def supertrend(df, period=10, multiplier=3): hl = (df['High'] + df['Low']) / 2 atr = df['High'].rolling(period).max() - df['Low'].rolling(period).min()
up = hl - multiplier * atr dn = hl + multiplier * atr df['ST'] = 0 df['ST'][0] = (df['High'][0] + df['Low'][0]) / 2 position = 'none' for i in range(1, len(df)): if df['Close'][i] > up[i]: if position != 'buy': position = 'buy' df['ST'][i] = dn[i] else: df['ST'][i] = max(df['ST'][i - 1], dn[i]) elif df['Close'][i] < dn[i]: if position != 'sell': position = 'sell' df['ST'][i] = up[i] else: df['ST'][i] = min(df['ST'][i - 1], up[i]) else: df['ST'][i] = df['ST'][i - 1] return dfnifty = supertrend(nifty) nifty.head()
dataset = nifty['Close'].values dataset = dataset.astype('float32') dataset = dataset.reshape(-1, 1) scaler = MinMaxScaler(feature_range=(0, 1)) dataset = scaler.fit_transform(dataset)
convert an array of values into a dataset matrix
def create_dataset(dataset, look_back=1): dataX, dataY = [], [] for i in range(len(dataset)-look_back-1): a = dataset[i:(i+look_back), 0] dataX.append(a) dataY.append(dataset[i + look_back, 0]) return np.array(dataX), np.array(dataY)
train_size = int(len(dataset) * 0.8) test_size = len(dataset) - train_size train, test = dataset[:train_size], dataset[train_size:]
look_back = 1 trainX, trainY = create_dataset(train, look_back) testX, testY = create_dataset(test, look_back)
trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1])) testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
model = Sequential() model.add(LSTM(100, input_shape=(1, look_back))) model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam') model.fit(trainX, trainY, epochs=200, batch_size=1, verbose=0)
trainPredict = model.predict(trainX) testPredict = model.predict(testX)
trainPredict = scaler.inverse_transform(trainPredict) trainY = scaler.inverse_transform([trainY]) testPredict = scaler.inverse_transform(testPredict) testY = scaler.inverse_transform([testY])
import matplotlib.pyplot as plt
trainPredictPlot = np.empty_like(dataset) trainPredictPlot[:, :] = np.nan trainPredictPlot[look_back:len(trainPredict)+look_back, :] = trainPredict
- Assistant
Based on the provided model, I can predict the price on 2021-01-02. Here is the updated code to get the prediction:
# Predict the price on 2021-01-02 last_close = dataset[-2:] # Take the last two closing prices last_close_scaled = scaler.transform(last_close) # Scale the last two closing prices last_close_input = np.reshape(last_close_scaled, (1, 1, 1)) # Reshape the input for the model prediction_scaled = model.predict(last_close_input) # Make the prediction prediction = scaler.inverse_transform(prediction_scaled) # Convert the prediction back to its original form print("Price prediction for 2021-01-02:", prediction[0][0])Please keep in mind that the model's accuracy depends on the structure and the input data. For a more accurate prediction, try using larger datasets and fine-tuning the model's parameters.
- User
- Assistant
I apologize for the mistake in the code. Since we are using
look_back = 1, it's not necessary to take the last two closing prices. Here's the corrected code for predicting the price on 2021-01-02:# Predict the price on 2021-01-02 last_close = dataset[-1:] # Take the last closing price last_close_scaled = scaler.transform(last_close) # Scale the last closing price last_close_input = np.reshape(last_close_scaled, (1, 1, 1)) # Reshape the input for the model prediction_scaled = model.predict(last_close_input) # Make the prediction prediction = scaler.inverse_transform(prediction_scaled) # Convert the prediction back to its original form print("Price prediction for 2021-01-02:", prediction[0][0])Now, this code should work without any errors. Please replace the previous prediction code block with the corrected version above.
- User
- Assistant
To evaluate the accuracy of the model, you can use root-mean-squared error (RMSE) as a metric. Comparing the RMSE values for training and test data can give an idea of how well the model has learned and generalized. To calculate the RMSE, you can use the following code:
from sklearn.metrics import mean_squared_error import math trainScore = math.sqrt(mean_squared_error(trainY[0], trainPredict[:,0])) print('Train Score: %.2f RMSE' % (trainScore)) testScore = math.sqrt(mean_squared_error(testY[0], testPredict[:,0])) print('Test Score: %.2f RMSE' % (testScore))Add the above code snippet after saving the model, and it will print the RMSE scores for both training and test data, giving you an idea of the model's performance. Keep in mind that these scores may not always be reflective of the model's performance in making future predictions, as it is only an evaluation metric on the available data.