import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import LSTM, Dense, Dropout
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
print("Missing values before cleaning:\n", df.isnull().sum())
df.dropna(inplace=True) # Or use df.fillna(method='ffill') for forward fill
print("Missing values after cleaning:\n", df.isnull().sum())
5. Feature Selection
Include 'Closing Price' as an input feature for better forecasting
def forecast_multivariate(model, X_input, scaler_y, n_steps=20):
"""
Predict the next n_steps closing prices based on X_input.
code
Parameters:
- model: Trained LSTM model
- X_input: The initial input sequence (scaled), shape=(time_steps, num_features)
- scaler_y: Scaler for the target variable
- n_steps: Number of future steps to predict
Returns:
- List of predicted values (original scale)
"""
predictions = []
X_current = X_input.copy()
for _ in range(n_steps):
# Predict the next closing price
pred_scaled = model.predict(X_current.reshape(1, X_current.shape[0], X_current.shape[1]))
predictions.append(pred_scaled[0, 0])
# Create a new feature vector for the next prediction
new_feature = X_current[-1].copy() # Copy the last time step
# Update 'Closing Price' with the predicted value
new_feature[-1] = pred_scaled # Replace the 'Closing Price' with prediction
# Append the new feature to the sequence and remove the first time step
X_current = np.append(X_current[1:], [new_feature.flatten()], axis=0)
# Inverse transform the predictions to original scale
predictions = scaler_y.inverse_transform(np.array(predictions).reshape(-1, 1))
return predictions.flatten()
Example Usage:
Using the last sequence from the test set to predict the next 20 steps