I have created a stock market prediction model based on super indication now in this you…
- User
I have created a stock market prediction model based on super indication now in this you need give code to make predictions for upcoming prices for next 5 days using the model also in y axis insted of time make it date:
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
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
testPredictPlot = np.empty_like(dataset) testPredictPlot[:, :] = np.nan testPredictPlot[len(trainPredict)+(look_back*2)+1:len(dataset)-1, :] = testPredict
plt.plot(scaler.inverse_transform(dataset), label='Actual') plt.plot(trainPredictPlot, label='Train Prediction') plt.plot(testPredictPlot, label='Test Prediction') plt.legend() plt.show()
model.save('my_model.h5')
- Assistant
To make predictions for the upcoming prices for the next 5 days using the model, you need to add the following code at the end of your script:
# Function to predict the next 'n' days prices def predict_next_n_days(model, data, n): predictions = [] data = np.array(data[-1 * look_back:]) for _ in range(n): pred = model.predict(data.reshape(1, 1, look_back)) data = np.concatenate((data[1:], pred), axis=0) predictions.append(pred) return scaler.inverse_transform(predictions) # Predict the next 5 days prices num_days = 5 predicted_prices = predict_next_n_days(model, dataset, num_days) # Add the predicted dates import datetime last_date_in_data = nifty.index[-1] predicted_dates = [last_date_in_data + datetime.timedelta(days=i) for i in range(1, num_days + 1)] # Plot the predictions plt.figure(figsize=(15, 5)) plt.plot(nifty.index, scaler.inverse_transform(dataset), label='Actual') plt.plot(predicted_dates, predicted_prices, label='Predicted', marker='o') plt.xlabel('Date') plt.ylabel('Price') plt.legend() plt.show()This code will plot the predicted prices for the next 5 days with dates on the x-axis. Make sure to adjust the plot size to display the predictions appropriately.
- User
ValueError Traceback (most recent call last) in <cell line: 3>() 1 # Predict the next 5 days prices 2 num_days = 5 ----> 3 predicted_prices = predict_next_n_days(model, dataset, num_days)
2 frames /usr/local/lib/python3.10/dist-packages/sklearn/utils/validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, estimator, input_name) 913 ) 914 if not allow_nd and array.ndim >= 3: --> 915 raise ValueError( 916 "Found array with dim %d. %s expected <= 2." 917 % (array.ndim, estimator_name)
ValueError: Found array with dim 3. None expected <= 2.
- Assistant
Apologies for the mistake, I misunderstood the input for the
predict_next_n_daysfunction. Instead ofdataset, we should usetestdata. Here's the corrected code:# Function to predict the next 'n' days prices def predict_next_n_days(model, data, n): predictions = [] data = np.array(data[-1 * look_back:]) for _ in range(n): pred = model.predict(data.reshape(1, 1, look_back)) data = np.concatenate((data[1:], pred), axis=0) predictions.append(pred) return scaler.inverse_transform(predictions) # Predict the next 5 days prices num_days = 5 predicted_prices = predict_next_n_days(model, test, num_days) # Add the predicted dates import datetime last_date_in_data = nifty.index[-1] predicted_dates = [last_date_in_data + datetime.timedelta(days=i) for i in range(1, num_days + 1)] # Plot the predictions plt.figure(figsize=(15, 5)) plt.plot(nifty.index, scaler.inverse_transform(dataset), label='Actual') plt.plot(predicted_dates, predicted_prices, label='Predicted', marker='o') plt.xlabel('Date') plt.ylabel('Price') plt.legend() plt.show()Replace
datasetwithtestin thepredicted_pricesline, and now it should work without any issues.