0% found this document useful (0 votes)
82 views14 pages

Implementing Time Series Stock Price Prediction With LSTM and Yfinance in Python - by SR - Medium

Tume series stock prediction

Uploaded by

aaron
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views14 pages

Implementing Time Series Stock Price Prediction With LSTM and Yfinance in Python - by SR - Medium

Tume series stock prediction

Uploaded by

aaron
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Open in app

Search

Be part of a better internet. Get 20% off membership for a limited time

Implementing Time Series Stock Price


Prediction with LSTM and yfinance in Python
SR · Follow
4 min read · Dec 22, 2023

Listen Share More

Let’s break down the code part by part:

1. Importing Libraries:

Use Case: Preparing the necessary tools for financial data analysis and neural
network modeling.

Application: This section sets up the environment with libraries such as


yfinance for data retrieval, numpy and pandas for data manipulation, and
MinMaxScaler , Sequential , LSTM , and Dense for building and training neural
networks.

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.

numpy : Provides support for large, multi-dimensional arrays and matrices,


which is commonly used in numerical operations.

pandas : A powerful library for data manipulation and analysis, particularly


useful for handling time series data.

MinMaxScaler : Part of scikit-learn, it scales data to a specified range (0 to 1 in this


case), which is important for neural network training.

Sequential , LSTM , Dense : Components of the Keras library, where Sequential is


used to initialize the neural network, LSTM represents the LSTM layer, and Dense

is used to add a fully connected layer to the neural network.

2. Downloading Historical Stock Data:

Use Case: Fetching historical stock prices for a specified period.

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:

stock_symbol : Specifies the stock symbol for which historical data is to be


downloaded (in this case, 'AAPL' for Apple).

start_date and end_date : Define the date range for which historical stock data
is to be retrieved.

yf.download() : Fetches historical stock data using Yahoo Finance API.

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.

scaler : Initializes a MinMaxScaler, which scales data between 0 and 1.

close_prices_scaled : Applies Min-Max scaling to normalize the closing prices.

4. Creating Input Data for LSTM:

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.

def create_lstm_data(data, time_steps=1):


x, y = [], []
for i in range(len(data) - time_steps):
x.append(data[i:(i + time_steps), 0])
y.append(data[i + time_steps, 0])
return np.array(x), np.array(y)

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

5. Setting Time Steps and Creating Input Data:

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.

6. Building 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:

model : Initializes a sequential neural network model.

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.

7. Training the Model:

Use Case: Optimizing the model’s parameters using historical data.

Application: This part trains the LSTM model using historical stock prices,
allowing the model to learn patterns and relationships within the data.

model.fit(x, y, epochs=50, batch_size=32)

Explanation:

Trains the LSTM model using the prepared input data ( x ) and target values ( y ).

epochs=50 : Specifies the number of training iterations.

batch_size=32 : Sets the number of samples per gradient update.

8. Predicting Future Stock Prices:

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:

future_dates : Generates future dates for prediction.

Extracts the last 10 closing prices to predict future prices.

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.

Application: The predicted prices are displayed in a structured format, allowing


users to assess and make decisions based on the model’s forecasts.

future_data = pd.DataFrame({'Date': future_dates, 'Predicted Price': predicted_


print(future_data)

Explanation:

Creates a DataFrame ( future_data ) with future dates and the corresponding


predicted prices.

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.

Python Lstm Yahoo Predictions Stock Market

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

Predicting Stock Prices with Machine Learning in Python: A Step-by-Step


Guide
Introduction

Jun 3 79

SR

Real-time Cryptocurrency Trading Bot: Candlestick Pattern Detection


with Python and CCXT
Full Code :

Jan 5 33 3
SR

Implementing Algorithmic Trading Strategies with Python: A Step-by-


Step Guide
Code part by part explanations and use case

Jan 8 101

SR

Predicting Stock Prices using LSTM and Yahoo Finance Data


Predicting stock prices is a challenging yet intriguing task in the field of machine learning. In
this blog post, we’ll explore how to use…
Dec 17, 2023 59

See all from SR

Recommended from Medium

Ayrat Murtazin

Predicting Stock Market with Python


A fast guide

Dec 28, 2023 24


SR

Implementing Algorithmic Trading Strategies with Python: A Step-by-


Step Guide
Code part by part explanations and use case

Jan 8 101

Lists

Coding & Development


11 stories · 663 saves

Predictive Modeling w/ Python


20 stories · 1309 saves

Practical Guides to Machine Learning


10 stories · 1577 saves

ChatGPT
21 stories · 687 saves
Shenggang Li in DataDrivenInvestor

Time Series Forecasting: A Comparative Analysis of SARIMAX, RNN,


LSTM, Prophet, and Transformer…
Assessing the Efficiency and Efficacy of Leading Forecasting Algorithms Across Diverse
Datasets

Apr 13 182 4

Sercan Bugra Gultekin

(5) Stock Price Prediction with ML in Python: ‘Sentiment Analysis’ for


Smarter Trading
Did you know that it’s possible to use sentiment analysis to evaluate stock news published on
trading websites?

Jun 10 13

Jermaine Matthew

XGBoost for stock trend & prices prediction


Using technical indicators as features, I use XGBRegressor from XGBoost library to predict
future stock prices.

Jan 17 276 3
Daniel Svoboda

Utilizing Attention Mechanism in an Encoder-Decoder LSTM Model for


Cryptocurrency Price Prediction

Apr 1 34

See more recommendations

You might also like