Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· OpenAIAi2 WildChat-4.8M (AI2)

Make a accurate stock market predictor for predicting closing price using LSTM model and…

  1. 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: 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.

  2. Assistant

    Here's a step-by-step guide on how to create a stock market predictor using LSTM with the Super trend indicator:

    1. Import necessary libraries:
    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    import datetime
    from sklearn.preprocessing import MinMaxScaler
    from keras.models import Sequential
    from keras.layers import Dense, LSTM, Dropout
    
    1. Load and preprocess the stock data:
    # Load the historical stock data
    stock_data = pd.read_csv('<your_data_csv_file>')
    stock_data['Date'] = pd.to_datetime(stock_data['Date'])
    stock_data.set_index('Date', inplace=True)
    
    # Calculate the Average True Range and Super Trend
    price_high_low = stock_data['High'] - stock_data['Low']
    price_high_close = abs(stock_data['High'] - stock_data['Close'].shift())
    price_low_close = abs(stock_data['Low'] - stock_data['Close'].shift())
    tr = np.maximum(price_high_low, np.maximum(price_high_close, price_low_close))
    atr = tr.rolling(window=14).mean()
    
    multiplier = 3
    stock_data['SuperTrend_Up'] = (stock_data['High'] + stock_data['Low']) / 2 - multiplier * atr
    stock_data['SuperTrend_Down'] = (stock_data['High'] + stock_data['Low']) / 2 + multiplier * atr
    
    super_trend = []
    for i in range(len(stock_data)):
        if i == 0:
            super_trend.append(stock_data['Close'].iloc[i])
        elif stock_data['Close'].iloc[i] > super_trend[i - 1]:
            super_trend.append(stock_data['SuperTrend_Up'].iloc[i])
        else:
            super_trend.append(stock_data['SuperTrend_Down'].iloc[i])
    
    stock_data['SuperTrend'] = super_trend
    
    1. Prepare the training and testing datasets:
    # Remove rows with missing data and select the 'Close' and 'SuperTrend' columns for training and testing
    stock_data = stock_data.dropna()
    data = stock_data[['Close', 'SuperTrend']].values
    
    # Scale the data
    scaler = MinMaxScaler(feature_range=(0, 1))
    scaled_data = scaler.fit_transform(data)
    
    # Choose number of time steps (e.g., 60 days) and split into training and testing datasets
    time_steps = 60
    train_data = scaled_data[:len(stock_data)-time_steps-1]
    test_data = scaled_data[len(stock_data)-time_steps-1:]
    
    # Prepare the input and output for the LSTM model
    x_train = []
    y_train = []
    x_test = []
    y_test = []
    
    for i in range(time_steps, len(train_data)):
        x_train.append(train_data[i-time_steps:i])
        y_train.append(train_data[i, 0])
    
    for i in range(time_steps, len(test_data)):
        x_test.append(test_data[i-time_steps:i])
        y_test.append(test_data[i, 0])
    
    x_train, y_train = np.array(x_train), np.array(y_train)
    x_test, y_test = np.array(x_test), np.array(y_test)
    
    1. Build and train the LSTM model:
    # Build the LSTM model
    model = Sequential()
    model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1], 2)))
    model.add(Dropout(0.2))
    model.add(LSTM(units=50))
    model.add(Dropout(0.2))
    model.add(Dense(1))
    
    # Compile and train the LSTM model
    model.compile(optimizer='adam', loss='mean_squared_error')
    model.fit(x_train, y_train, epochs=100, batch_size=32)
    
    1. Predict the stock closing prices and plot the results:
    # Perform predictions using the LSTM model
    predicted_prices = model.predict(x_test)
    predicted_prices = np.concatenate((predicted_prices, x_test[:, -1, 1].reshape(-1, 1)), axis=1)
    predicted_prices = scaler.inverse_transform(predicted_prices)[:, 0]
    
    # Plot the actual vs predicted closing prices
    plt.figure(figsize=(14, 6))
    plt.plot(y_test, color='blue', label='Actual Stock Price')
    plt.plot(predicted_prices, color='red', label='Predicted Stock Price')
    plt.title('Stock Price Prediction')
    plt.xlabel('Time')
    plt.ylabel('Stock Price')
    plt.legend()
    plt.show()
    

    Remember to replace '<your_data_csv_file>' with the path to your stock data CSV file. The stock data should have columns: 'Date', 'Open', 'High', 'Low', 'Close', and 'Volume'. The predictor will use the LSTM model to predict the closing prices and plot the actual and predicted values.

  3. User

    Use yfinance as dataset

  4. Assistant

    To use yfinance as the dataset, we first need to install the yfinance library. You can install it using pip:

    pip install yfinance
    

    Now, you can use yfinance to download historical stock data and follow the same steps to create the stock market predictor:

    1. Import necessary libraries and load stock data from Yahoo finance:
    import yfinance as yf
    
    # Download historical stock data
    stock_symbol = 'AAPL'  # Replace this with the desired stock symbol
    start_date = '2000-01-01'  # Replace this with the desired start date
    end_date = datetime.datetime.today().strftime('%Y-%m-%d')  # Today's date
    
    stock_data = yf.download(stock_symbol, start=start_date, end=end_date)
    
    # Reset the index and use the 'Date' column as the index
    stock_data.reset_index(inplace=True)
    stock_data.set_index('Date', inplace=True)
    

    Then, you can follow the same steps as before to preprocess the stock data, prepare the training and testing datasets, build and train the LSTM model, predict the stock closing prices, and plot the results.

    You can find the complete code snippet here:

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    import datetime
    from sklearn.preprocessing import MinMaxScaler
    from keras.models import Sequential
    from keras.layers import Dense, LSTM, Dropout
    import yfinance as yf
    
    # Download historical stock data
    stock_symbol = 'AAPL'  # Replace this with the desired stock symbol
    start_date = '2000-01-01'  # Replace this with the desired start date
    end_date = datetime.datetime.today().strftime('%Y-%m-%d')  # Today's date
    
    stock_data = yf.download(stock_symbol, start=start_date, end=end_date)
    
    # Reset the index and use the 'Date' column as the index
    stock_data.reset_index(inplace=True)
    stock_data.set_index('Date', inplace=True)
    
    # Calculate the Average True Range and Super Trend
    price_high_low = stock_data['High'] - stock_data['Low']
    price_high_close = abs(stock_data['High'] - stock_data['Close'].shift())
    price_low_close = abs(stock_data['Low'] - stock_data['Close'].shift())
    tr = np.maximum(price_high_low, np.maximum(price_high_close, price_low_close))
    atr = tr.rolling(window=14).mean()
    
    multiplier = 3
    stock_data['SuperTrend_Up'] = (stock_data['High'] + stock_data['Low']) / 2 - multiplier * atr
    stock_data['SuperTrend_Down'] = (stock_data['High'] + stock_data['Low']) / 2 + multiplier * atr
    
    super_trend = []
    for i in range(len(stock_data)):
        if i == 0:
            super_trend.append(stock_data['Close'].iloc[i])
        elif stock_data['Close'].iloc[i] > super_trend[i - 1]:
            super_trend.append(stock_data['SuperTrend_Up'].iloc[i])
        else:
            super_trend.append(stock_data['SuperTrend_Down'].iloc[i])
    
    stock_data['SuperTrend'] = super_trend
    
    # Remove rows with missing data and select the 'Close' and 'SuperTrend' columns for training and testing
    stock_data = stock_data.dropna()
    data = stock_data[['Close', 'SuperTrend']].values
    
    # Scale the data
    scaler = MinMaxScaler(feature_range=(0, 1))
    scaled_data = scaler.fit_transform(data)
    
    # Choose number of time steps (e.g., 60 days) and split into training and testing datasets
    time_steps = 60
    train_data = scaled_data[:len(stock_data)-time_steps-1]
    test_data = scaled_data[len(stock_data)-time_steps-1:]
    
    # Prepare the input and output for the LSTM model
    x_train = []
    y_train = []
    x_test = []
    y_test = []
    
    for i in range(time_steps, len(train_data)):
        x_train.append(train_data[i-time_steps:i])
        y_train.append(train_data[i, 0])
    
    for i in range(time_steps, len(test_data)):
        x_test.append(test_data[i-time_steps:i])
        y_test.append(test_data[i, 0])
    
    x_train, y_train = np.array(x_train), np.array(y_train)
    x_test, y_test = np.array(x_test), np.array(y_test)
    
    # Build the LSTM model
    model = Sequential()
    model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1], 2)))
    model.add(Dropout(0.2))
    model.add(LSTM(units=50))
    model.add(Dropout(0.2))
    model.add(Dense(1))
    
    # Compile and train the LSTM model
    model.compile(optimizer='adam', loss='mean_squared_error')
    model.fit(x_train, y_train, epochs=100, batch_size=32)
    
    # Perform predictions using the LSTM model
    predicted_prices = model.predict(x_test)
    predicted_prices = np.concatenate((predicted_prices, x_test[:, -1, 1].reshape(-1, 1)), axis=1)
    predicted_prices = scaler.inverse_transform(predicted_prices)[:, 0]
    
    # Plot the actual vs predicted closing prices
    plt.figure(figsize=(14, 6))
    plt.plot(y_test, color='blue', label='Actual Stock Price')
    plt.plot(predicted_prices, color='red', label='Predicted Stock Price')
    plt.title('Stock Price Prediction')
    plt.xlabel('Time')
    plt.ylabel('Stock Price')
    plt.legend()
    plt.show()
    
  5. User

    In this code Im getting nothing in the plot its blank: import numpy as np import pandas as pd import matplotlib.pyplot as plt import datetime from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import Dense, LSTM, Dropout import yfinance as yf

    Download historical stock data

    stock_symbol = 'AAPL' # Replace this with the desired stock symbol start_date = '2000-01-01' # Replace this with the desired start date end_date = datetime.datetime.today().strftime('2023-06-01') # Today's date

    stock_data = yf.download(stock_symbol, start=start_date, end=end_date)

    stock_data['Close'].plot(title='AAPL Closing Price', figsize=(15,6)) plt.show()

    Reset the index and use the 'Date' column as the index

    stock_data.reset_index(inplace=True) stock_data.set_index('Date', inplace=True)

    Calculate the Average True Range and Super Trend

    price_high_low = stock_data['High'] - stock_data['Low'] price_high_close = abs(stock_data['High'] - stock_data['Close'].shift()) price_low_close = abs(stock_data['Low'] - stock_data['Close'].shift()) tr = np.maximum(price_high_low, np.maximum(price_high_close, price_low_close)) atr = tr.rolling(window=14).mean()

    multiplier = 3 stock_data['SuperTrend_Up'] = (stock_data['High'] + stock_data['Low']) / 2 - multiplier * atr stock_data['SuperTrend_Down'] = (stock_data['High'] + stock_data['Low']) / 2 + multiplier * atr

    super_trend = [] for i in range(len(stock_data)): if i == 0: super_trend.append(stock_data['Close'].iloc[i]) elif stock_data['Close'].iloc[i] > super_trend[i - 1]: super_trend.append(stock_data['SuperTrend_Up'].iloc[i]) else: super_trend.append(stock_data['SuperTrend_Down'].iloc[i])

    stock_data['SuperTrend'] = super_trend

    stock_data.info()

    Remove rows with missing data and select the 'Close' and 'SuperTrend' columns for training and testing

    stock_data = stock_data.dropna() data = stock_data[['Close', 'SuperTrend']].values stock_data.head()

    Scale the data

    scaler = MinMaxScaler(feature_range=(0, 1)) scaled_data = scaler.fit_transform(data)

    Choose number of time steps (e.g., 60 days) and split into training and testing datasets

    time_steps = 60 train_data = scaled_data[:len(stock_data)-time_steps-1] test_data = scaled_data[len(stock_data)-time_steps-1:]

    Prepare the input and output for the LSTM model

    x_train = [] y_train = [] x_test = [] y_test = []

    for i in range(time_steps, len(train_data)): x_train.append(train_data[i-time_steps:i]) y_train.append(train_data[i, 0])

    for i in range(time_steps, len(test_data)): x_test.append(test_data[i-time_steps:i]) y_test.append(test_data[i, 0])

    x_train, y_train = np.array(x_train), np.array(y_train) x_test, y_test = np.array(x_test), np.array(y_test)

    Build the LSTM model

    model = Sequential() model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1], 2))) model.add(Dropout(0.2)) model.add(LSTM(units=50)) model.add(Dropout(0.2)) model.add(Dense(1))

    Compile and train the LSTM model

    model.compile(optimizer='adam', loss='mean_squared_error') model.fit(x_train, y_train, epochs=100, batch_size=32)

    Perform predictions using the LSTM model

    predicted_prices = model.predict(x_test) predicted_prices = np.concatenate((predicted_prices, x_test[:, -1, 1].reshape(-1, 1)), axis=1) predicted_prices = scaler.inverse_transform(predicted_prices)[:, 0]

    Plot the actual vs predicted closing prices

    plt.figure(figsize=(14, 6)) plt.plot(y_test, color='blue', label='Actual Stock Price') plt.plot(predicted_prices, color='red', label='Predicted Stock Price') plt.title('Stock Price Prediction') plt.xlabel('Time') plt.ylabel('Stock Price') plt.legend() plt.show()

  6. Assistant

    It seems there might be a problem with the indexing of the testing dataset when plotting the actual vs predicted stock prices. Also, the end date was incorrectly set to today's date.

    Here's the revised plotting part of your code:

    # Perform predictions using the LSTM model
    predicted_prices = model.predict(x_test)
    predicted_prices = np.concatenate((predicted_prices, x_test[:, -1, 1].reshape(-1, 1)), axis=1)
    predicted_prices = scaler.inverse_transform(predicted_prices)[:, 0]
    
    # Create a dataframe for actual prices and predicted prices
    actual_prices = pd.DataFrame(stock_data[len(stock_data) - len(y_test):]['Close'])
    actual_prices['predicted'] = predicted_prices
    actual_prices.columns = ['Actual', 'Predicted']
    
    # Plot the actual vs predicted closing prices
    plt.figure(figsize=(14, 6))
    plt.plot(actual_prices['Actual'].values, color='blue', label='Actual Stock Price')
    plt.plot(actual_prices['Predicted'].values, color='red', label='Predicted Stock Price')
    plt.title('Stock Price Prediction')
    plt.xlabel('Time')
    plt.ylabel('Stock Price')
    plt.legend()
    plt.show()
    

    I have replaced the original plotting code with the above lines. Now, it should plot the actual and predicted stock prices correctly. Make sure to fit the date properly. In your code you had:

    end_date = datetime.datetime.today().strftime('2023-06-01')  # Today's date
    

    But it should be:

    end_date = datetime.datetime.today().strftime('%Y-%m-%d')  # Today's date
    
  7. User

    Please correct the code im still getting a blank plot for this code: Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import datetime from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import Dense, LSTM, Dropout import yfinance as yf

    Download historical stock data

    stock_symbol = 'AAPL' # Replace this with the desired stock symbol start_date = '2000-01-01' # Replace this with the desired start date end_date = datetime.datetime.today().strftime('%Y-%m-%d') # Today's date

    stock_data = yf.download(stock_symbol, start=start_date, end=end_date)

    stock_data['Close'].plot(title='AAPL Closing Price', figsize=(15,6)) plt.show()

    Reset the index and use the 'Date' column as the index

    stock_data.reset_index(inplace=True) stock_data.set_index('Date', inplace=True)

    Calculate the Average True Range and Super Trend

    price_high_low = stock_data['High'] - stock_data['Low'] price_high_close = abs(stock_data['High'] - stock_data['Close'].shift()) price_low_close = abs(stock_data['Low'] - stock_data['Close'].shift()) tr = np.maximum(price_high_low, np.maximum(price_high_close, price_low_close)) atr = tr.rolling(window=14).mean()

    multiplier = 3 stock_data['SuperTrend_Up'] = (stock_data['High'] + stock_data['Low']) / 2 - multiplier * atr stock_data['SuperTrend_Down'] = (stock_data['High'] + stock_data['Low']) / 2 + multiplier * atr

    super_trend = [] for i in range(len(stock_data)): if i == 0: super_trend.append(stock_data['Close'].iloc[i]) elif stock_data['Close'].iloc[i] > super_trend[i - 1]: super_trend.append(stock_data['SuperTrend_Up'].iloc[i]) else: super_trend.append(stock_data['SuperTrend_Down'].iloc[i])

    stock_data['SuperTrend'] = super_trend

    stock_data.info()

    Remove rows with missing data and select the 'Close' and 'SuperTrend' columns for training and testing

    stock_data = stock_data.dropna() data = stock_data[['Close', 'SuperTrend']].values stock_data.head()

    Scale the data

    scaler = MinMaxScaler(feature_range=(0, 1)) scaled_data = scaler.fit_transform(data)

    Choose number of time steps (e.g., 60 days) and split into training and testing datasets

    time_steps = 60 train_data = scaled_data[:len(stock_data)-time_steps-1] test_data = scaled_data[len(stock_data)-time_steps-1:]

    Prepare the input and output for the LSTM model

    x_train = [] y_train = [] x_test = [] y_test = []

    for i in range(time_steps, len(train_data)): x_train.append(train_data[i-time_steps:i]) y_train.append(train_data[i, 0])

    for i in range(time_steps, len(test_data)): x_test.append(test_data[i-time_steps:i]) y_test.append(test_data[i, 0])

    x_train, y_train = np.array(x_train), np.array(y_train) x_test, y_test = np.array(x_test), np.array(y_test)

    Build the LSTM model

    model = Sequential() model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1], 2))) model.add(Dropout(0.2)) model.add(LSTM(units=50)) model.add(Dropout(0.2)) model.add(Dense(1))

    Compile and train the LSTM model

    model.compile(optimizer='adam', loss='mean_squared_error') model.fit(x_train, y_train, epochs=100, batch_size=32)

    Perform predictions using the LSTM model

    predicted_prices = model.predict(x_test) predicted_prices = np.concatenate((predicted_prices, x_test[:, -1, 1].reshape(-1, 1)), axis=1) predicted_prices = scaler.inverse_transform(predicted_prices)[:, 0]

    Create a dataframe for actual prices and predicted prices

    actual_prices = pd.DataFrame(stock_data[len(stock_data) - len(y_test):]['Close']) actual_prices['predicted'] = predicted_prices actual_prices.columns = ['Actual', 'Predicted']

    Plot the actual vs predicted closing prices

    plt.figure(figsize=(14, 6)) plt.plot(actual_prices['Actual'].values, color='blue', label='Actual Stock Price') plt.plot(actual_prices['Predicted'].values, color='red', label='Predicted Stock Price') plt.title('Stock Price Prediction') plt.xlabel('Time') plt.ylabel('Stock Price') plt.legend() plt.show()

  8. Assistant

    Apologies for the mistake in the previous response. After analyzing your code, I have found an issue in selecting data for plotting. Here's the corrected version of how to populate the 'actual_prices' DataFrame and plot the actual vs predicted closing prices.

    Replace this part in your code:

    # Create a dataframe for actual prices and predicted prices
    actual_prices = pd.DataFrame(stock_data[len(stock_data) - len(y_test):]['Close'])
    actual_prices['predicted'] = predicted_prices
    actual_prices.columns = ['Actual', 'Predicted']
    

    With the following:

    # Create a dataframe for actual prices and predicted prices
    actual_prices = pd.DataFrame(stock_data.iloc[-len(y_test):, :]['Close'])
    actual_prices['Predicted'] = predicted_prices
    actual_prices.columns = ['Actual', 'Predicted']
    

    Now, the complete updated script should work as expected:

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    import datetime
    from sklearn.preprocessing import MinMaxScaler
    from keras.models import Sequential
    from keras.layers import Dense, LSTM, Dropout
    import yfinance as yf
    
    # Download historical stock data
    stock_symbol = 'AAPL'  # Replace this with the desired stock symbol
    start_date = '2000-01-01'  # Replace this with the desired start date
    end_date = datetime.datetime.today().strftime('%Y-%m-%d')  # Today's date
    
    stock_data = yf.download(stock_symbol, start=start_date, end=end_date)
    
    stock_data['Close'].plot(title='AAPL Closing Price', figsize=(15,6))
    plt.show()
    
    # Reset the index and use the 'Date' column as the index
    stock_data.reset_index(inplace=True)
    stock_data.set_index('Date', inplace=True)
    
    # Calculate the Average True Range and Super Trend
    price_high_low = stock_data['High'] - stock_data['Low']
    price_high_close = abs(stock_data['High'] - stock_data['Close'].shift())
    price_low_close = abs(stock_data['Low'] - stock_data['Close'].shift())
    tr = np.maximum(price_high_low, np.maximum(price_high_close, price_low_close))
    atr = tr.rolling(window=14).mean()
    
    multiplier = 3
    stock_data['SuperTrend_Up'] = (stock_data['High'] + stock_data['Low']) / 2 - multiplier * atr
    stock_data['SuperTrend_Down'] = (stock_data['High'] + stock_data['Low']) / 2 + multiplier * atr
    
    super_trend = []
    for i in range(len(stock_data)):
        if i == 0:
            super_trend.append(stock_data['Close'].iloc[i])
        elif stock_data['Close'].iloc[i] > super_trend[i - 1]:
            super_trend.append(stock_data['SuperTrend_Up'].iloc[i])
        else:
            super_trend.append(stock_data['SuperTrend_Down'].iloc[i])
    
    stock_data['SuperTrend'] = super_trend
    
    # Remove rows with missing data and select the 'Close' and 'SuperTrend' columns for training and testing
    stock_data = stock_data.dropna()
    data = stock_data[['Close', 'SuperTrend']].values
    
    # Scale the data
    scaler = MinMaxScaler(feature_range=(0, 1))
    scaled_data = scaler.fit_transform(data)
    
    # Choose number of time steps (e.g., 60 days) and split into training and testing datasets
    time_steps = 60
    train_data = scaled_data[:len(stock_data)-time_steps-1]
    test_data = scaled_data[len(stock_data)-time_steps-1:]
    
    # Prepare the input and output for the LSTM model
    x_train = []
    y_train = []
    x_test = []
    y_test = []
    
    for i in range(time_steps, len(train_data)):
        x_train.append(train_data[i-time_steps:i])
        y_train.append(train_data[i, 0])
    
    for i in range(time_steps, len(test_data)):
        x_test.append(test_data[i-time_steps:i])
        y_test.append(test_data[i, 0])
    
    x_train, y_train = np.array(x_train), np.array(y_train)
    x_test, y_test = np.array(x_test), np.array(y_test)
    
    # Build the LSTM model
    model = Sequential()
    model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1], 2)))
    model.add(Dropout(0.2))
    model.add(LSTM(units=50))
    model.add(Dropout(0.2))
    model.add(Dense(1))
    
    # Compile and train the LSTM model
    model.compile(optimizer='adam', loss='mean_squared_error')
    model.fit(x_train, y_train, epochs=100, batch_size=32)
    
    # Perform predictions using the LSTM model
    predicted_prices = model.predict(x_test)
    predicted_prices = np.concatenate((predicted_prices, x_test[:, -1, 1].reshape(-1, 1)), axis=1)
    predicted_prices = scaler.inverse_transform(predicted_prices)[:, 0]
    
    # Create a dataframe for actual prices and predicted prices
    actual_prices = pd.DataFrame(stock_data.iloc[-len(y_test):, :]['Close'])
    actual_prices['Predicted'] = predicted_prices
    actual_prices.columns = ['Actual', 'Predicted']
    
    # Plot the actual vs predicted closing prices
    plt.figure(figsize=(14, 6))
    plt.plot(actual_prices['Actual'].values, color='blue', label='Actual Stock Price')
    plt.plot(actual_prices['Predicted'].values, color='red', label='Predicted Stock Price')
    plt.title('Stock Price Prediction')
    plt.xlabel('Time')
    plt.ylabel('Stock Price')
    plt.legend()
    plt.show()
    

    Running this script should generate the plot of actual vs. predicted stock prices.

  9. User

    I have write a code for stock market prediction but i think this code is incorrect as im not getting anything in plot ie the plot is empty please correct the code also the time axis starts with -0.04 which is not possible give a correct code for predicting the stock market also plot for daywise not time wise: Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import datetime from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import Dense, LSTM, Dropout import yfinance as yf

    Download historical stock data

    stock_symbol = 'AAPL' # Replace this with the desired stock symbol start_date = '2000-01-01' # Replace this with the desired start date end_date = datetime.datetime.today().strftime('%Y-%m-%d') # Today's date

    stock_data = yf.download(stock_symbol, start=start_date, end=end_date)

    stock_data['Close'].plot(title='AAPL Closing Price', figsize=(15,6)) plt.show()

    Reset the index and use the 'Date' column as the index

    stock_data.reset_index(inplace=True) stock_data.set_index('Date', inplace=True)

    Calculate the Average True Range and Super Trend

    price_high_low = stock_data['High'] - stock_data['Low'] price_high_close = abs(stock_data['High'] - stock_data['Close'].shift()) price_low_close = abs(stock_data['Low'] - stock_data['Close'].shift()) tr = np.maximum(price_high_low, np.maximum(price_high_close, price_low_close)) atr = tr.rolling(window=14).mean()

    multiplier = 3 stock_data['SuperTrend_Up'] = (stock_data['High'] + stock_data['Low']) / 2 - multiplier * atr stock_data['SuperTrend_Down'] = (stock_data['High'] + stock_data['Low']) / 2 + multiplier * atr

    super_trend = [] for i in range(len(stock_data)): if i == 0: super_trend.append(stock_data['Close'].iloc[i]) elif stock_data['Close'].iloc[i] > super_trend[i - 1]: super_trend.append(stock_data['SuperTrend_Up'].iloc[i]) else: super_trend.append(stock_data['SuperTrend_Down'].iloc[i])

    stock_data['SuperTrend'] = super_trend

    stock_data.info()

    Remove rows with missing data and select the 'Close' and 'SuperTrend' columns for training and testing

    stock_data = stock_data.dropna() data = stock_data[['Close', 'SuperTrend']].values stock_data.head()

    Scale the data

    scaler = MinMaxScaler(feature_range=(0, 1)) scaled_data = scaler.fit_transform(data)

    Choose number of time steps (e.g., 60 days) and split into training and testing datasets

    time_steps = 60 train_data = scaled_data[:len(stock_data)-time_steps-1] test_data = scaled_data[len(stock_data)-time_steps-1:]

    Prepare the input and output for the LSTM model

    x_train = [] y_train = [] x_test = [] y_test = []

    for i in range(time_steps, len(train_data)): x_train.append(train_data[i-time_steps:i]) y_train.append(train_data[i, 0])

    for i in range(time_steps, len(test_data)): x_test.append(test_data[i-time_steps:i]) y_test.append(test_data[i, 0])

    x_train, y_train = np.array(x_train), np.array(y_train) x_test, y_test = np.array(x_test), np.array(y_test)

    Build the LSTM model

    model = Sequential() model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1], 2))) model.add(Dropout(0.2)) model.add(LSTM(units=50)) model.add(Dropout(0.2)) model.add(Dense(1))

    Compile and train the LSTM model

    model.compile(optimizer='adam', loss='mean_squared_error') model.fit(x_train, y_train, epochs=100, batch_size=32)

    Perform predictions using the LSTM model

    predicted_prices = model.predict(x_test) predicted_prices = np.concatenate((predicted_prices, x_test[:, -1, 1].reshape(-1, 1)), axis=1) predicted_prices = scaler.inverse_transform(predicted_prices)[:, 0]

    Create a dataframe for actual prices and predicted prices

    actual_prices = pd.DataFrame(stock_data.iloc[-len(y_test):, :]['Close']) actual_prices['Predicted'] = predicted_prices actual_prices.columns = ['Actual', 'Predicted']

    Plot the actual vs predicted closing prices

    plt.figure(figsize=(14, 6)) plt.plot(actual_prices['Actual'].values, color='blue', label='Actual Stock Price') plt.plot(actual_prices['Predicted'].values, color='red', label='Predicted Stock Price') plt.title('Stock Price Prediction') plt.xlabel('Time') plt.ylabel('Stock Price') plt.legend() plt.show()

  10. Assistant

    Thank you for pointing out the issue. I've identified the problem - it's with the indexing of the 'y_test' values for plotting. We need to create a date range for the testing period to make the x-axis display dates instead of numbers. I've corrected the plotting section of your code. Please replace it with the following code:

    # Create a dataframe for actual prices and predicted prices
    test_dates = pd.date_range(start=stock_data.index[-len(y_test)], end=stock_data.index[-1], freq='B')
    actual_prices = pd.DataFrame(stock_data.loc[test_dates]['Close'])
    actual_prices['Predicted'] = predicted_prices
    actual_prices.columns = ['Actual', 'Predicted']
    
    # Plot the actual vs predicted closing prices
    plt.figure(figsize=(14, 6))
    plt.plot(actual_prices.index, actual_prices['Actual'].values, color='blue', label='Actual Stock Price')
    plt.plot(actual_prices.index, actual_prices['Predicted'].values, color='red', label='Predicted Stock Price')
    plt.title('Stock Price Prediction')
    plt.xlabel('Date')
    plt.ylabel('Stock Price')
    plt.xticks(rotation=45)
    plt.legend()
    plt.show()
    

    This code creates a date range for the testing period and updates the 'actual_prices' DataFrame to include these dates as the index. The x-axis of the plot should now display dates instead of negative numbers. Make sure to use this updated code in your script to see the plot with correct dates on the x-axis.

    Notice I also changed the xticks rotation to 45 degrees for better readability of date labels.