<jupyter_start><jupyter_text>LSTM refers to Long Short Term Memory Networks. It is a type of recurrent neural network that is commonly used for regression and time series forecasting in ML. It can memorize data for long periods, which differentiates LSTM neural networks from other neural networks. In this notebook, we will learn how to predict stock prices with LSTM!<jupyter_code>!pip install yfinance<jupyter_output>Requirement already satisfied: yfinance in /usr/local/lib/python3.7/dist-packages (0.1.70)
Requirement already satisfied: lxml>=4.5.1 in /usr/local/lib/python3.7/dist-packages (from yfinance) (4.8.0)
Requirement already satisfied: multitasking>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from yfinance) (0.0.10)
Requirement already satisfied: pandas>=0.24.0 in /usr/local/lib/python3.7/dist-packages (from yfinance) (1.3.5)
Requirement already satisfied: requests>=2.26 in /usr/local/lib/python3.7/dist-packages (from yfinance) (2.27.1)
Requirement already satisfied: numpy>=1.15 in /usr/local/lib/python3.7/dist-packages (from yfinance) (1.21.5)
Requirement already satisfied: pytz>=2017.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24.0->yfinance) (2018.9)
Requirement already satisfied: python-dateutil>=2.7.3 in /usr/local/lib/python3.7/dist-packages (from pandas>=0.24.0->yfinance) (2.8.2)
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.7/dist-packages (f[...]<jupyter_text>Stock Price Prediction with LSTMUsing LSTM is one of the best machine learning approaches for time series forecasting. LSTMs are recurrent neural networks designed to remember data for a longer period. So, whenever you are working on a problem where your neural network fails to memorize data, you can use LSTM neural network. You can read more about LSTMs here (https://web.stanford.edu/class/cs379c/archive/2018/class_messages_listing/content/Artificial_Neural_Network_Technology_Tutorials/OlahLSTM-NEURAL-NETWORK-TUTORIAL-15.pdf)Now in this section, I will take you through the task of Stock price prediction with LSTM using the Python programming language. I will start this task by importing all the necessary Python libraries and collecting the latest stock price data of Apple:<jupyter_code>import pandas as pd
import yfinance as yf
import datetime
from datetime import date, timedelta
today = date.today()
d1 = today.strftime("%Y-%m-%d")
end_date = d1
d2 = date.today() - timedelta(days=5000)
d2 = d2.strftime("%Y-%m-%d")
start_date = d2
data = yf.download('AAPL', 
                      start=start_date, 
                      end=end_date, 
                      progress=False)
data["Date"] = data.index
data = data[["Date", "Open", "High", "Low", "Close", 
             "Adj Close", "Volume"]]
data.reset_index(drop=True, inplace=True)
data.tail()<jupyter_output><empty_output><jupyter_text>A candlestick chart gives a clear picture of the increase and decrease in stock prices, so let’s visualize a candlestick chart of the data before moving further:<jupyter_code>import plotly.graph_objects as go
figure = go.Figure(data=[go.Candlestick(x=data["Date"],
                                        open=data["Open"], 
                                        high=data["High"],
                                        low=data["Low"], 
                                        close=data["Close"])])
figure.update_layout(title = "Apple Stock Price Analysis", 
                     xaxis_rangeslider_visible=False)
figure.show()
correlation = data.corr()
print(correlation["Close"].sort_values(ascending=False))<jupyter_output>Close        1.000000
High         0.999887
Low          0.999885
Adj Close    0.999873
Open         0.999774
Volume      -0.485205
Name: Close, dtype: float64<jupyter_text>Training LSTM for Stock Price Prediction - Now I will start with training an LSTM model for predicting stock prices. I will first split the data into training and test sets:<jupyter_code>x = data[["Open", "High", "Low", "Volume"]]
y = data["Close"]
x = x.to_numpy()
y = y.to_numpy()
y = y.reshape(-1, 1)

from sklearn.model_selection import train_test_split
xtrain, xtest, ytrain, ytest = train_test_split(x, y, test_size=0.2, random_state=42)
from keras.models import Sequential
from keras.layers import Dense, LSTM

# Preparing LSTM model 
model = Sequential()
model.add(LSTM(128, return_sequences=True, input_shape= (xtrain.shape[1], 1)))
model.add(LSTM(64, return_sequences=False))
model.add(Dense(25))
model.add(Dense(1))
model.summary()
# Train our model for stock price prediction

model.compile(optimizer='adam', loss='mean_squared_error')
history = model.fit(xtrain, ytrain, batch_size=1, epochs=30)
# list all data in model
print(history.history.keys())
# summarize history for loss
plt.plot(history.history['loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()<jupyter_output><empty_output><jupyter_text>Now let’s test this model by giving input values according to the features that we have used to train this model and predicting the final result:<jupyter_code>import numpy as np

# features = [Open, High, Low, Adj Close, Volume]
features = np.array([[177.089996, 180.419998, 177.070007, 74919600]])
model.predict(features)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11188811188811189, 'fraction_numerical': 0.03761103761103761, 'mean_word_length': 4.183153770812929, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 31, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 1}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 5, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '476749', 'license': 'MIT', 'n_tokens_mistral': 1772, 'n_tokens_neox': 1629, 'n_words': 497, 'path': 'Stock_Price_perdiction_using_LSTM.ipynb', 'repo_name': 'Janani-harshu/Machine_Learning_Projects', 'size': '5291'}