<jupyter_start><jupyter_text><jupyter_code># Long Short Term Memory to predict  Apple Inc using past 60 days
import math
import pandas_datareader as web
import numpy as np
import pandas as pd
from datetime import date, timedelta
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')

TICKER = 'AAPL'
START='2012-01-01'
yesterday = date.today() - timedelta(days=1)
END = yesterday.strftime('%Y-%m-%d')
DATA_SOURCE='yahoo'

TODAY = date.today().strftime('%Y-%m-%d')
# Get the stock quote
df = web.DataReader(TICKER, data_source=DATA_SOURCE, start=START, end=END)
# Show the data

# Visualize closing price history
plt.figure(figsize=(16, 8))
plt.title('Close Price History')
plt.plot(df['Close'])
plt.xlabel('Date', fontsize=18)
plt.ylabel('Close Price USD ($)', fontsize=8)
# plt.show()

# Create a new dataframe with only the Close  column
data = df.filter(['Close'])
# Convert the dataframe to a numpy array
dataset = data.values
# Get the number of rows to train a model on
training_data_len = math.ceil( len(dataset) * .8)

print(training_data_len)

# Scale the data
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(dataset)

# Create the data set
# Create the scaled
train_data = scaled_data[0:training_data_len, :]
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<= 61 :
    print(x_train)
    print(y_train)

# Convert the x_train and y_train to numpy arrays
x_train, y_train = np.array(x_train), np.array(y_train)

# Reshape the data
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
x_train.shape

# Build the 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))

# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')

model.fit(x_train, y_train, batch_size=1, epochs=1)

# Create the testing data set
# Create a new array containing scaled values from index 1543 to 2003
test_data = scaled_data[training_data_len - 60:, :]
# Create the data sets x_test and 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])

# Convert data to numpy array
x_test = np.array(x_test)

# Reshape the data because LSTM model expects 3D

x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))

# Get predictions
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)
print("Root mean squared error: ")
print(rmse)

# Plot the data
train = data[:training_data_len]
valid = data[training_data_len:]
valid['Predictions'] = predictions


# Visualize the data
plt.figure(figsize=(16, 8))
plt.title('Model')
plt.xlabel('Date', fontsize=18)
plt.ylabel('Close Price USD ($)', fontsize=8)
plt.plot(train['Close'])
plt.plot(valid[['Close', 'Predictions']])
plt.legend(['Train', 'Val', 'Predictions'], loc='lower right')
plt.show()

# Visualize the data
plt.figure(figsize=(16, 8))
plt.title('Model')
plt.xlabel('Date', fontsize=18)
plt.ylabel('Close Price USD ($)', fontsize=8)
plt.plot(train['Close'])
plt.plot(valid[['Predictions']])
plt.legend(['Train', 'Val', 'Predictions'], loc='lower right')

# Get the quote
ticker_quote = web.DataReader(TICKER, data_source=DATA_SOURCE, start=START, end=END)
# Create a new dataframe
new_df = ticker_quote.filter(['Close'])
# Get the last 60 day closing price values and convert the dataframe to an array
last_60_days = new_df[-60:].values
# Scale the data to be values between 0 and 1
last_60_days_scales = scaler.transform(last_60_days)
# Create an empty list
X_test = []
# Append past 60 days
X_test.append(last_60_days_scales)
# Append the 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 the predicted scaled price
pred_price = model.predict(X_test)
# undo the scaling
pred_price = scaler.inverse_transform(pred_price)
print(pred_price)

# Get the quote
ticker_quote2 = web.DataReader(TICKER, data_source=DATA_SOURCE, start=TODAY, end=TODAY)
print(ticker_quote2['Close'])<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1328437917222964, 'fraction_numerical': 0.021361815754339118, 'mean_word_length': 6.001557632398754, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 5, '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': '61698', 'license': 'Apache-2.0', 'n_tokens_mistral': 1707, 'n_tokens_neox': 1597, 'n_words': 423, 'path': 'AAPL.ipynb', 'repo_name': 'MichaelFriedberg/AlphaPy', 'size': '4494'}