Using LSTM Networks for Stock Price Time Series Prediction with Keras
This tutorial demonstrates how to apply an LSTM deep‑learning model in Python to forecast stock closing prices, covering data acquisition, preprocessing, model construction, training, evaluation, and visualization of results for time‑series prediction.
Goal: Learn to use deep learning for time series forecasting.
Learning content: LSTM network and a practical example of predicting stock prices.
Code example:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM
from tensorflow.keras.optimizers import Adam
from tushare.pro_api import ProApi
# Set Tushare API Token
token = 'your_tushare_token' # replace with your token
pro = ProApi(token)
# Get stock data
ts_code = '002594.SZ' # BYD stock code
start_date = '2018-01-01'
end_date = '2023-06-05'
df = pro.daily(ts_code=ts_code, start_date=start_date, end_date=end_date)
# Sort by date and select closing price
df['trade_date'] = pd.to_datetime(df['trade_date'])
df.set_index('trade_date', inplace=True)
df.sort_index(inplace=True)
df = df[['close']]
print(f"Stock data:\n{df.head()}")
# Standardize data
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(df)
df_scaled = pd.DataFrame(scaled_data, columns=['close'], index=df.index)
print(f"Standardized data:\n{df_scaled.head()}")
# Create time‑series dataset
def create_dataset(data, time_step=60):
X, y = [], []
for i in range(len(data) - time_step - 1):
a = data[i:(i + time_step), 0]
X.append(a)
y.append(data[i + time_step, 0])
return np.array(X), np.array(y)
time_step = 60
X, y = create_dataset(scaled_data, time_step)
# Split into train and test sets
train_size = int(len(X) * 0.8)
test_size = len(X) - train_size
X_train, X_test = X[0:train_size], X[train_size:len(X)]
y_train, y_test = y[0:train_size], y[train_size:len(y)]
# Reshape for LSTM
X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], 1)
X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], 1)
# Build LSTM model
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(time_step, 1)))
model.add(LSTM(50, return_sequences=False))
model.add(Dense(25))
model.add(Dense(1))
model.summary()
# Compile and train
model.compile(optimizer=Adam(learning_rate=0.001), loss='mean_squared_error')
history = model.fit(X_train, y_train, epochs=50, batch_size=64, validation_data=(X_test, y_test))
# Evaluate
loss = model.evaluate(X_test, y_test)
print(f"Test loss: {loss:.4f}")
# Plot training loss
plt.figure(figsize=(12, 4))
plt.plot(history.history['loss'], label='Training loss')
plt.plot(history.history['val_loss'], label='Validation loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.title('Training and Validation Loss')
plt.show()
# Predict
y_pred = model.predict(X_test)
y_pred_inv = scaler.inverse_transform(y_pred)
y_test_inv = scaler.inverse_transform(y_test.reshape(-1, 1))
print(f"First predictions:\n{y_pred_inv[:10].flatten()}")
print(f"First true values:\n{y_test_inv[:10].flatten()}")
# Plot predictions
plt.figure(figsize=(12, 6))
plt.plot(df.index[-len(y_test):], y_test_inv, label='Actual')
plt.plot(df.index[-len(y_test):], y_pred_inv, label='Predicted')
plt.xlabel('Date')
plt.ylabel('Close price')
plt.legend()
plt.title('Stock Price Prediction')
plt.show()Practice: Run the above script to fetch historical data, preprocess it, train the LSTM model, evaluate performance, and visualize both loss curves and prediction results.
Conclusion: After completing this exercise you should be able to build and train a simple LSTM model with Keras to forecast stock prices, and you are encouraged to apply these techniques to real projects.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.