file_path = r"C:\Users\jack8\OneDrive\stock cow ai\data\enhanced_stock_price_ma.csv"
data = pd.read_csv(file_path, parse_dates=['Date'])
檢查資料
print(data.head())
print(data.isnull().sum())
2. 選擇特徵和目標,包含日期欄位
features = ['Date', 'Opening Price', 'Highest Price', 'Lowest Price', 'Closing Price', 'MA_5', 'MA_20']
target = 'Closing Price'
data = data[features]
###幫我寫lstm,幫含early_stopping,還有MAPE,繪製結果請用英文寫標題等
Assistant
Sure! Below is a complete example of how to build an LSTM model for predicting the closing price of a stock using your dataset. This implementation includes data preprocessing, model building with early stopping, calculating Mean Absolute Percentage Error (MAPE), and plotting the results with English titles and labels.
python
# Import necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_absolute_percentage_error
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense
from tensorflow.keras.callbacks import EarlyStopping
# 1. Load and preprocess the data
file_path = r"C:\Users\jack8\OneDrive\stock cow ai\data\enhanced_stock_price_ma.csv"
data = pd.read_csv(file_path, parse_dates=['Date'])
# Display the first few rows and check for missing values
print(data.head())
print(data.isnull().sum())
# 2. Select features and target
# It's common to exclude the 'Date' column from features for modeling purposes
features = ['Opening Price', 'Highest Price', 'Lowest Price', 'Closing Price', 'MA_5', 'MA_20']
target = 'Closing Price'
data = data[features]
# Sort the data by date if not already sorted
# Assuming the original data is sorted; if not, uncomment the following line:
# data = data.sort_values('Date')
# Handle missing values if any (e.g., forward fill)
data.fillna(method='ffill', inplace=True)
# 3. Feature Scaling
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data)
# 4. Create sequences for LSTM
def create_sequences(data, sequence_length):
X = []
y = []
for i in range(sequence_length, len(data)):
X.append(data[i-sequence_length:i])
y.append(data[i][3]) # 'Closing Price' is the 4th feature (index 3)
return np.array(X), np.array(y)
sequence_length = 60 # You can adjust this value
X, y = create_sequences(scaled_data, sequence_length)
# 5. Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, shuffle=False
)
# 6. Build the LSTM model
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(LSTM(units=50))
model.add(Dense(1))
# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error', metrics=['mean_absolute_percentage_error'])
# 7. Implement Early Stopping
early_stop = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)
# 8. Train the model
history = model.fit(
X_train, y_train,
epochs=100,
batch_size=32,
validation_split=0.1,
callbacks=[early_stop],
verbose=1
)
# 9. Make predictions
predictions = model.predict(X_test)
# Inverse transform the scaled data to get actual prices
# Since only 'Closing Price' was used as the target, we need to invert the scaling for that feature
# Create a scaler for the target
scaler_target = MinMaxScaler()
scaler_target.min_, scaler_target.scale_ = scaler.min_[3], scaler.scale_[3]
y_test_inverse = scaler_target.inverse_transform(y_test.reshape(-1, 1))
predictions_inverse = scaler_target.inverse_transform(predictions)
# 10. Calculate MAPE
mape = mean_absolute_percentage_error(y_test_inverse, predictions_inverse)
print(f"Mean Absolute Percentage Error (MAPE): {mape * 100:.2f}%")
# 11. Plot the results
plt.figure(figsize=(14, 7))
plt.plot(y_test_inverse, color='blue', label='Actual Closing Price')
plt.plot(predictions_inverse, color='red', label='Predicted Closing Price')
plt.title('Actual vs Predicted Closing Prices')
plt.xlabel('Time')
plt.ylabel('Closing Price')
plt.legend()
plt.show()
Explanation of the Steps:
Import Libraries: Import all necessary libraries for data manipulation, visualization, and building the LSTM model.
Load and Preprocess Data:
Loading: Read the CSV file and parse the 'Date' column as datetime.
Selection: Select relevant features for the model. It's common to exclude the 'Date' from features used in LSTM as it doesn't carry numerical information unless transformed.
Sorting: Ensure data is sorted chronologically.
Handling Missing Values: Forward fill any missing values to maintain data continuity.
Feature Scaling: Scale the features between 0 and 1 using MinMaxScaler to help the LSTM model converge faster.
Create Sequences:
LSTM models require input in sequences. Here, each input sequence consists of sequence_length timesteps.
The target is the 'Closing Price' at the next timestep.
Train-Test Split: Split the data into training and testing sets without shuffling to maintain the time series order.
Build the LSTM Model:
Layers: Two LSTM layers are used followed by a Dense layer for output.
Compilation: Use 'adam' optimizer and 'mean_squared_error' as loss. Additionally, track 'mean_absolute_percentage_error' as a metric.
Early Stopping: Implement early stopping to prevent overfitting. Training stops if there's no improvement in validation loss for 10 consecutive epochs.
Train the Model: Fit the model on the training data with a validation split of 10%.
Make Predictions:
Predict on the test set.
Inverse transform the scaled predictions and actual values to get them back to the original scale.
Calculate MAPE: Compute the Mean Absolute Percentage Error to evaluate the model's accuracy.
Plot the Results: Visualize the actual vs. predicted closing prices with appropriate titles and labels in English.
Additional Notes:
Sequence Length: The sequence_length parameter determines how many past timesteps the model looks at to make a prediction. You can experiment with different values (e.g., 30, 60, 90) to see which works best for your dataset.
Scaling the Target: It's crucial to scale the target variable in the same way as the features to ensure accurate inverse transformation.
Model Complexity: The number of LSTM layers and units can be adjusted based on the complexity of your data and the performance of the model.
Evaluation Metrics: While MAPE is useful, you might also consider other metrics like Root Mean Squared Error (RMSE) or Mean Absolute Error (MAE) for a comprehensive evaluation.
Further Improvements:
Hyperparameter Tuning: Adjust learning rates, batch sizes, and other hyperparameters for better performance.
Dropout Layers: Introduce dropout layers to prevent overfitting.
Additional Features: Incorporate more features or engineered features that might help the model capture underlying patterns better.
I hope this helps you build and understand your LSTM model for stock price prediction!