Make a accurate stock market predictor for predicting closing price using LSTM model and…
- User
Make a accurate stock market predictor for predicting closing price using LSTM model and include super trend indicator for better results also make plot showing actual and predicted value (use dataset using yfinance for NIFTY): Supertrend Indicator: Super trend Indicator: What Does It Mean? The Super trend indicator is a trend-following indicator that works just like moving averages. This indicator is typically represented by the price, and you can determine the latest trend by its positioning on the price. This basic indicator is designed by using only two parameters – multiplier and period.
The default parameters when you design the Super trend indicator plan are 3 for the multiplier and 10 for ATR (Average True Range). The ATR plays a crucial role here, as the Super trend indicator leverages the ATR for computing its value. It helps signal the degree or extent of price volatility.
Super trend Indicator: How Does It Work? A super trend indicator is one of the most commonly used indicators for setting your selling and buying points at the most accurate levels. However, the question still remains: how does it work to accomplish something like that?
You should know that two lines – a green line and a red line – compose the Super trend indicator. These lines enable you to evaluate the following:
The trend direction, Whether to buy or sell and, in either case, when to do so. To plot and indicate the lines, the super trend indicator leverages the ATR along with the multiplicator. This enables you to set or position market entries based on volatility and momentum.
And when it comes to what chart is best for the Super trend indicator to function, you can independently utilize it on almost every timeline you consider a trend to be developing. A super trend is a lagging indicator, implying that any well-built trend will boost the indicator’s performance.
Super trend Indicator: Parameters to Know About As you have read earlier, 10 and 3 are the two default parameters. You must remember that any modifications to these numerical values will influence the utilization of the Super trend indicator. No trading indicator comes with the best setting.
If you change more and more settings, the trading system may become over-optimized for that specific period. Keep a note of the following pointers:
The market noise will be removed with higher settings when there’s a risk of fewer trading signals. The indicator will become more reactive/responsive to the price with smaller settings, resulting in more signals. Super trend Indicator Formula Here is the Super trend indicator formula that helps you calculate this indicator:
Down = [(High + Low / 2) – Multiplier] x ATR Up = [(High + Low / 2) + Multiplier] x ATR To calculate the ATR, follow this formula:
[(Previous ATR x 13) + Existing TR]/14 14 resembles a period in this equation. Thus, the ATR is determined by multiplying 13 by the past ATR. Then, add the result to the latest TR and divide it by the period. So, it’s clear that when it comes to the Super trend indicator, ATR plays a major role in it.
Super trend Indicator: How to Use It for Identifying Buy & Sell Signals The super trend is an excellent trending indicator that functions exceptionally in both downtrends and uptrends. You can easily identify and locate the buy-sell signal whenever the indicator flips or rotates over the closing price.
When the super trend closes below the price point and the color changes to green, the buy signal is generated. Meanwhile, a sell signal is generated when the color changes to red and the Super trend closes above the price point
- Assistant
To implement a stock market predictor using an LSTM model and incorporate the Super Trend indicator, we need to follow these steps:
Step 1: Import necessary libraries
import numpy as np import pandas as pd import yfinance as yf import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import Dense, LSTMStep 2: Download NIFTY historical data
nifty = yf.download('^NSEI', start='2000-01-01') nifty['Close'].plot(title='NIFTY Closing Price', figsize=(15,6)) plt.show()Step 3: Prepare the dataset
data = nifty.filter(['Close']) np_data = data.values # Scale the data to 0-1 range scaler = MinMaxScaler(feature_range=(0,1)) scaled_data = scaler.fit_transform(np_data)Step 4: Create an LSTM model
def create_lstm_model(): model = Sequential() model.add(LSTM(50, return_sequences=True, input_shape=(60,1))) model.add(LSTM(50, return_sequences=False)) model.add(Dense(25)) model.add(Dense(1)) model.compile(optimizer='adam', loss='mean_squared_error') return model lstm_model = create_lstm_model()Step 5: Train the LSTM model
x_train, y_train = prepare_training_data(scaled_data) lstm_model.fit(x_train, y_train, batch_size=1, epochs=3)Step 6: Predict the stock closing price
test_data = prepare_test_data(scaled_data) predictions = lstm_model.predict(test_data) # Revert scaling predictions = scaler.inverse_transform(predictions)Step 7: Calculate the Super Trend
def calculate_supertrend(data, period=10, multiplier=3): data['TR'] = np.maximum((data['High'] - data['Low']), np.maximum(abs(data['High'] - data['Close'].shift(1)), abs(data['Low'] - data['Close'].shift(1)))) data['ATR'] = data['TR'].rolling(period).mean() data['SuperTrend_UP'] = ((data['High'] + data['Low']) / 2) + (multiplier * data['ATR']) data['SuperTrend_DOWN'] = ((data['High'] + data['Low']) / 2) - (multiplier * data['ATR']) data['SuperTrend'] = np.nan for i in range(period, len(data)): if np.isnan(data['SuperTrend'].iloc[i - 1]): if data['Close'].iloc[i - 1] > data['SuperTrend_UP'].iloc[i - 1]: data['SuperTrend'].iloc[i] = data['SuperTrend_DOWN'].iloc[i] else: data['SuperTrend'].iloc[i] = data['SuperTrend_UP'].iloc[i] else: if data['Close'].iloc[i - 1] > data['SuperTrend'].iloc[i - 1]: data['SuperTrend'].iloc[i] = max(data['SuperTrend_DOWN'].iloc[i], data['SuperTrend'].iloc[i - 1]) else: data['SuperTrend'].iloc[i] = min(data['SuperTrend_UP'].iloc[i], data['SuperTrend'].iloc[i - 1]) return data nifty_with_supertrend = calculate_supertrend(nifty)Step 8: Plot actual and predicted stock with Super Trend indicator
plt.figure(figsize=(15, 6)) plt.plot(nifty_with_supertrend['Close'], label='Actual NIFTY Closing Price') plt.plot(nifty_with_supertrend.index[-len(test_data):], predictions, label='Predicted NIFTY Closing Price') plt.plot(nifty_with_supertrend['SuperTrend'], label='Super Trend Indicator', linestyle='--') plt.legend() plt.title('NIFTY Actual vs. Predicted Closing Price with Super Trend Indicator') plt.show()