<jupyter_start><jupyter_text>***Stock Market Analysis & Prediction***<jupyter_code>#Libraries To Be Imported
import math
import pandas_datareader as web
import numpy as np
import pandas as pd
import tensorflow
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense , LSTM
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
#Geting Stock Data 
df = web.DataReader('AAPL', data_source = 'yahoo', start = '2012-01-01', end = '2019-12-12')
#Showing Stock Data
df
#Getting Number Of Rows & Columns From The Data
df.shape
#Visualise Closing Price
plt.figure(figsize=(16,8))
plt.title('Closing Price')
plt.plot(df['Close'])
plt.xlabel('Year', fontsize = 20)
plt.ylabel('Close Price USD ($)', fontsize = 20)
plt.show()
#Creating Close Column DataFrame
data = df.filter(['Close'])
#Convert The DataFrame To A Numpy Array
dataset = data.values
#Get Number Of Rows To Train The Model On
training_data_len = math.ceil(len(dataset)*.9)
training_data_len
#Scaling Data
scaler = MinMaxScaler(feature_range=(0,1))
scaled_data = scaler.fit_transform(dataset)
scaled_data
#Creating Trained Data Set
#Creating Scaled Training Data Set
train_data = scaled_data[0:training_data_len , :]
#Splitting Data Into x_train & y_train Data Sets
x_train = []
y_train = []
for i in range(60,len(train_data)):
  x_train.append(train_data[i-60:i,0])
  y_train.append(train_data[i,0])
  if i<=60:
    print(x_train)
    print(y_train)
    print()
#Convert x_train & y_train Dataset To Numpy Arrays
x_train, y_train = np.array(x_train), np.array(y_train)
#Reshaping Data
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
x_train.shape
#Building Long Short-Term Memory(LSTM) Model
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(x_train.shape[1], 1)))
model.add(LSTM(50, return_sequences=False))
model.add(Dense(25))
model.add(Dense(1))
#Compiling The Model
model.compile(optimizer='adam', loss='mean_squared_error')
#Training The Model
model.fit(x_train, y_train, batch_size=1, epochs=1)
#Create Testing Dataset
#Create New Array Containing Scaled Values From index 1740 To 2000
test_data = scaled_data[training_data_len - 60: , :]
#Now Creating Data Sets x_test & y_test
x_test = []
y_test = dataset[training_data_len:, :]
for i in range(60, len(test_data)):
  x_test.append(test_data[i-60:i, 0])
#Converting The Data Into A Numpy Array
x_test = np.array(x_test)
#Reshaping The Data
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
#Get Models Predicted Price Values
predictions = model.predict(x_test)
predictions = scaler.inverse_transform(predictions)
#Get The Root Mean Squared Error (RMSE)
rmse = np.sqrt(np.mean(predictions - y_test)**2)
rmse
#Plot The Data
train = data[:training_data_len]
valid = data[training_data_len:]
valid['Predictions'] = predictions
#Visualizing The Data
plt.figure(figsize=(16,8))
plt.title('Prediction Model')
plt.xlabel('Year', fontsize=20)
plt.ylabel('Close Price USD ($)', fontsize = 20)
plt.plot(train['Close'])
plt.plot(valid[['Close', 'Predictions']])
plt.legend(['Train', 'Val', 'Predictions'], loc='upper left')
plt.show()
#Show The Valid & Predicted Prices
valid
#Get Predicted Quote
apple_quote = web.DataReader('AAPL', data_source = 'yahoo', start = '2012-01-01', end = '2019-12-12')
#Create New Dataframe
new_df = apple_quote.filter(['Close'])
#Get The Last 60 Day Closing Price Values & Convert The DataFrame To An Array
last_60_days = new_df[-60:].values
#Scale The Data To Be Values Between 0 & 1
last_60_days_scaled = scaler.transform(last_60_days)
#Creating An Empty List
X_test = []
#Append Past 60 Days
X_test.append(last_60_days_scaled)
#Convert X_test Data Set To A Numpy Array
X_test = np.array(X_test)
#Reshape The Data
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
#Get Predicted Scaled Price
pred_price = model.predict(X_test)
#Undo Scaling
pred_price = scaler.inverse_transform(pred_price)
print(pred_price)
#Get Real Quote
apple_quote1 = web.DataReader('AAPL', data_source='yahoo', start='2019-12-12', end='2019-12-12')
print(apple_quote1['Close'])<jupyter_output>Date
2019-12-12    67.864998
Name: Close, dtype: float64
{'fraction_non_alphanumeric': 0.12907059662467316, 'fraction_numerical': 0.03470406465414785, 'mean_word_length': 6.408450704225352, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '174866', 'license': 'MIT', 'n_tokens_mistral': 1631, 'n_tokens_neox': 1495, 'n_words': 396, 'path': 'Stock Market Analysis & Prediction.ipynb', 'repo_name': 'Nmane1612/Nihar-Mane', 'size': '4207'}