Implementing Time Series Stock Price Prediction With LSTM and Yfinance in Python - by SR - Medium
Implementing Time Series Stock Price Prediction With LSTM and Yfinance in Python - by SR - Medium
Search
Be part of a better internet. Get 20% off membership for a limited time
1. Importing Libraries:
Use Case: Preparing the necessary tools for financial data analysis and neural
network modeling.
import yfinance as yf
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import LSTM, Dense
Explanation:
yfinance : This library is used to download historical stock data from Yahoo
Finance.
Application: Investors, traders, and analysts can use this to gather data for a
particular stock, enabling various analyses and predictions.
stock_symbol = 'AAPL'
start_date = '2020–01–01'
end_date = '2021–01–01'
data = yf.download(stock_symbol, start=start_date, end=end_date)
Explanation:
start_date and end_date : Define the date range for which historical stock data
is to be retrieved.
3. Data Preprocessing:
Use Case: Preparing the historical stock data for input to a machine learning
model.
Application: This section extracts and scales the closing prices, a crucial step in
preparing the data for the LSTM model, ensuring that it is on a consistent scale
for training.
close_prices = data['Close'].values.reshape(-1, 1)
scaler = MinMaxScaler(feature_range=(0, 1))
close_prices_scaled = scaler.fit_transform(close_prices)
Explanation:
close_prices : Extracts the closing prices from the downloaded data and
reshapes them.
Use Case: Structuring the data into sequences for training the LSTM model.
Application: This function defines the input sequences (X) and corresponding
target values (y) for training the LSTM model, which is essential for capturing
temporal patterns in the data.
Explanation:
create_lstm_data : Defines a function to create input sequences for the LSTM
model.
The function takes historical stock prices ( data ) and a specified number of
time_steps to create input sequences x and corresponding target values y
Use Case: Defining the number of time steps for the LSTM model and reshaping
the data.
Application: This part sets the time steps, a hyperparameter affecting the
memory of the LSTM. Reshaping the data ensures that it conforms to the input
format expected by the LSTM layer.
time_steps = 10
x, y = create_lstm_data(close_prices_scaled, time_steps)
x = np.reshape(x, (x.shape[0], x.shape[1], 1))
Explanation:
time_steps : Sets the number of time steps for the LSTM model (in this case, 10).
x, y : Creates input data ( x ) and target values ( y ) using the previously defined
function.
Reshapes the input data to the required format for the LSTM model.
Use Case: Constructing a neural network architecture suitable for time series
prediction.
Application: The model architecture is designed with two LSTM layers and one
dense layer. This configuration is suitable for capturing and learning complex
patterns in sequential data like stock prices.
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(x.shape[1], 1)))
model.add(LSTM(units=50))
model.add(Dense(units=1))
model.compile(optimizer='adam', loss='mean_squared_error')
Explanation:
Adds two LSTM layers with 50 units each and a dense layer with 1 unit.
Compiles the model using the Adam optimizer and mean squared error as the
loss function.
Application: This part trains the LSTM model using historical stock prices,
allowing the model to learn patterns and relationships within the data.
Explanation:
Trains the LSTM model using the prepared input data ( x ) and target values ( y ).
Use Case: Utilizing the trained model to make predictions for future stock
prices.
Application: The code predicts future stock prices based on the last available
historical data, providing insights for potential market movements.
future_dates = pd.date_range(start=end_date, periods=30)
last_prices = close_prices[-time_steps:]
last_prices_scaled = scaler.transform(last_prices.reshape(-1, 1))
x_pred = np.array([last_prices_scaled[-time_steps:, 0]])
x_pred = np.reshape(x_pred, (x_pred.shape[0], x_pred.shape[1], 1))
predicted_prices_scaled = model.predict(x_pred)
predicted_prices = scaler.inverse_transform(predicted_prices_scaled)
Explanation:
Scales the last prices and prepares the input data for prediction.
Uses the trained LSTM model to predict future prices and inverse transforms the
scaled predictions.
9. Displaying Predictions:
Use Case: Visualizing and presenting the predicted future stock prices.
Explanation:
Prints the DataFrame, providing a readable format for the predicted future
prices.
Remember that this is a basic example, and real-world stock price prediction
involves more sophisticated models, feature engineering, and careful evaluation.
The code provided is for educational purposes and may need adjustments for
different scenarios.
Follow
Written by SR
129 Followers
15-year-old enthusiast passionate about tech, code, and creative writing. Sharing my journey on Medium. 🚀
| Code | Tech | Writing | Malaysian |
More from SR
SR
Jun 3 79
SR
Jan 5 33 3
SR
Jan 8 101
SR
Ayrat Murtazin
Jan 8 101
Lists
ChatGPT
21 stories · 687 saves
Shenggang Li in DataDrivenInvestor
Apr 13 182 4
Jun 10 13
Jermaine Matthew
Jan 17 276 3
Daniel Svoboda
Apr 1 34