๐ Stock Price Prediction Using TensorFlow and LSTM
A model designed using Tensorflow and Keras to implement LSTM model
Description
Predicting stock prices using AI is a powerful application of deep learning. In this tutorial, weโll walk through a complete project that uses LSTM (Long Short-Term Memory) networks to predict the future price of a stock, using TensorFlow and Keras.
โ Step 1: Install Required Libraries
Install the required Python libraries using pip:
pip install yfinance numpy pandas scikit-learn matplotlib tensorflow
๐ Step 2: Import the Required Libraries
import yfinance as yf
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 LSTM, Dense, Dropout
๐ Step 3: Load Historical Stock Data
We’ll use Yahoo Finance to fetch historical closing prices of Apple (AAPL).
df = yf.download('AAPL', start='2015-01-01', end='2023-12-31')
df = df[['Close']]
df.head()
๐งผ Step 4: Data Preprocessing
Normalize the data and prepare it for training.
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(df)
train_data = scaled_data[0:int(len(scaled_data) * 0.8), :]
def create_dataset(data, time_step=60):
x, y = [], []
for i in range(time_step, len(data)):
x.append(data[i-time_step:i, 0])
y.append(data[i, 0])
return np.array(x), np.array(y)
X_train, y_train = create_dataset(train_data)
X_train = X_train.reshape((X_train.shape[0], X_train.shape[1], 1))
๐ง Step 5: Build the LSTM Model
Hereโs how we define the LSTM-based neural network model:
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(X_train.shape[1], 1)))
model.add(Dropout(0.2))
model.add(LSTM(50))
model.add(Dropout(0.2))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mean_squared_error')
model.summary()
๐ Step 6: Train the Model
Train the model using the historical stock price data.
model.fit(X_train, y_train, epochs=10, batch_size=32)
๐งช Step 7: Make Predictions on Test Data
Now test the model using the remaining data and see how well it performs.
test_data = scaled_data[int(len(scaled_data) * 0.8) - 60:]
X_test, y_test = create_dataset(test_data)
X_test = X_test.reshape((X_test.shape[0], X_test.shape[1], 1))
predictions = model.predict(X_test)
predictions = scaler.inverse_transform(predictions)
real_prices = scaler.inverse_transform(y_test.reshape(-1, 1))
๐ Step 8: Plot Actual vs Predicted Prices
Visualize the predicted stock prices against the actual prices.
plt.figure(figsize=(12,6))
plt.plot(real_prices, color='blue', label='Actual Price')
plt.plot(predictions, color='red', label='Predicted Price')
plt.title('Stock Price Prediction')
plt.xlabel('Time')
plt.ylabel('Price')
plt.legend()
plt.show()
๐ฎ Bonus: Predict the Next Day’s Price
Want to know the stock price for the next day?
last_60_days = scaled_data[-60:]
last_60_days = last_60_days.reshape((1, 60, 1))
next_price = model.predict(last_60_days)
print("Predicted next day's price:", scaler.inverse_transform(next_price))
๐ง Conclusion
This basic LSTM model gives a solid introduction to time series forecasting using TensorFlow. You can improve accuracy by:
- Including more features (Open, High, Low, Volume)
- Using more layers or training for more epochs
- Tuning hyperparameters
Review
Write a ReviewThere are no reviews yet.