import pandas as pd
import numpy as np

import matplotlib.pyplot as plt
from matplotlib.pylab import rcParams
from tensorflow.python.keras.losses import mean_squared_error
from tensorflow.python.keras.optimizers import adam

rcParams['figure.figsize'] = 20, 10

from keras.models import Sequential
from keras.layers import LSTM, Dropout, Dense

from sklearn.preprocessing import MinMaxScaler

# Apple Historical Data from July 25th, 2020 to July 26, 2021
df = pd.read_csv('data/HistoricalData_1627345793457.csv')

# Preprocessing to just use first two columns in csv file
df = df[['Date', 'Close/Last']]

print(df.head())

print(df.dtypes)

# Get rid of the '$' from the 'Close/Last' column
df = df.replace({'\$': ''}, regex=True)

# Convert 'Close/Last' data type to float
df = df.astype({'Close/Last': float})
df['Date'] = pd.to_datetime(df.Date, format="%m/%d/%Y")

print(df.head())
print(df.dtypes)

# Define df's index value as 'Date' Column
df.index = df['Date']

# Line chart for data we have thus far
plt.plot(df['Close/Last'], label='Close Price History')

# Data Preparation
df = df.sort_index(ascending=True, axis=0)

data = pd.DataFrame(index=range(0, len(df)), columns=['Date', 'Close/Last'])

for i in range(0, len(data)):
    data['Date'][i] = df['Date'][i]
    data['Close/Last'][i] = df['Close/Last'][i]

print(data.head())

# Min-Max Scaler
scaler = MinMaxScaler(feature_range=(0, 1))

data.index = data.Date
data.drop('Date', axis=1, inplace=True)

final_data = data.values
train_data = final_data[0:200, :]
valid_data = final_data[0:200, :]

scaled_data = scaler.fit_transform(final_data)
x_train_data, y_train_data = [], []
for i in range(60, len(train_data)):
    x_train_data.append(scaled_data[i - 60: i, 0])
    y_train_data.append(scaled_data[i, 0])

# Defining LSTM Model
lstm_model = Sequential()
lstm_model.add(LSTM(units=50, return_sequences=True, input_shape=(np.shape(x_train_data)[1], 1)))
lstm_model.add(LSTM(units=50))
lstm_model.add(Dense(1))

model_data = data[len(data) - len(valid_data) - 60:].values
model_data = model_data.reshape(-1, 1)
model_data = scaler.transform(model_data)

# Training and Testing
lstm_model.compile(loss=mean_squared_error, optimizer=adam)
lstm_model.fit(x_train_data, y_train_data, epochs=1, batch_size=1, verbose=2)

X_test = []
for i in range(60, model_data.shape[0]):
    X_test.append(model_data[i - 60:i, 0])
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))

# Prediction Function
predicted_stock_price = lstm_model.predict(X_test)
predicted_stock_price = scaler.inverse_transform(predicted_stock_price)

train_data = data[:200]
valid_data = data[200:]
valid_data['Predictions'] = predicted_stock_price
plt.plot(train_data['Close/Last'])
plt.plot(valid_data[['Close/Last', 'Predictions']])

plt.show()

6b659fbd0905e5be5b69a3b4cf962ebb971f9509
<mask token>

<mask token>
print(df.head())
print(df.dtypes)
<mask token>
print(df.head())
print(df.dtypes)
<mask token>
plt.plot(df['Close/Last'], label='Close Price History')
<mask token>
for i in range(0, len(data)):
    data['Date'][i] = df['Date'][i]
    data['Close/Last'][i] = df['Close/Last'][i]
print(data.head())
<mask token>
data.drop('Date', axis=1, inplace=True)
<mask token>
for i in range(60, len(train_data)):
    x_train_data.append(scaled_data[i - 60:i, 0])
    y_train_data.append(scaled_data[i, 0])
<mask token>
lstm_model.add(LSTM(units=50, return_sequences=True, input_shape=(np.shape(
    x_train_data)[1], 1)))
lstm_model.add(LSTM(units=50))
lstm_model.add(Dense(1))
<mask token>
lstm_model.compile(loss=mean_squared_error, optimizer=adam)
lstm_model.fit(x_train_data, y_train_data, epochs=1, batch_size=1, verbose=2)
<mask token>
for i in range(60, model_data.shape[0]):
    X_test.append(model_data[i - 60:i, 0])
<mask token>
plt.plot(train_data['Close/Last'])
plt.plot(valid_data[['Close/Last', 'Predictions']])
plt.show()

<mask token>
rcParams['figure.figsize'] = 20, 10
<mask token>
df = pd.read_csv('data/HistoricalData_1627345793457.csv')
df = df[['Date', 'Close/Last']]
print(df.head())
print(df.dtypes)
df = df.replace({'\\$': ''}, regex=True)
df = df.astype({'Close/Last': float})
df['Date'] = pd.to_datetime(df.Date, format='%m/%d/%Y')
print(df.head())
print(df.dtypes)
df.index = df['Date']
plt.plot(df['Close/Last'], label='Close Price History')
df = df.sort_index(ascending=True, axis=0)
data = pd.DataFrame(index=range(0, len(df)), columns=['Date', 'Close/Last'])
for i in range(0, len(data)):
    data['Date'][i] = df['Date'][i]
    data['Close/Last'][i] = df['Close/Last'][i]
print(data.head())
scaler = MinMaxScaler(feature_range=(0, 1))
data.index = data.Date
data.drop('Date', axis=1, inplace=True)
final_data = data.values
train_data = final_data[0:200, :]
valid_data = final_data[0:200, :]
scaled_data = scaler.fit_transform(final_data)
x_train_data, y_train_data = [], []
for i in range(60, len(train_data)):
    x_train_data.append(scaled_data[i - 60:i, 0])
    y_train_data.append(scaled_data[i, 0])
lstm_model = Sequential()
lstm_model.add(LSTM(units=50, return_sequences=True, input_shape=(np.shape(
    x_train_data)[1], 1)))
lstm_model.add(LSTM(units=50))
lstm_model.add(Dense(1))
model_data = data[len(data) - len(valid_data) - 60:].values
model_data = model_data.reshape(-1, 1)
model_data = scaler.transform(model_data)
lstm_model.compile(loss=mean_squared_error, optimizer=adam)
lstm_model.fit(x_train_data, y_train_data, epochs=1, batch_size=1, verbose=2)
X_test = []
for i in range(60, model_data.shape[0]):
    X_test.append(model_data[i - 60:i, 0])
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
predicted_stock_price = lstm_model.predict(X_test)
predicted_stock_price = scaler.inverse_transform(predicted_stock_price)
train_data = data[:200]
valid_data = data[200:]
valid_data['Predictions'] = predicted_stock_price
plt.plot(train_data['Close/Last'])
plt.plot(valid_data[['Close/Last', 'Predictions']])
plt.show()

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pylab import rcParams
from tensorflow.python.keras.losses import mean_squared_error
from tensorflow.python.keras.optimizers import adam
rcParams['figure.figsize'] = 20, 10
from keras.models import Sequential
from keras.layers import LSTM, Dropout, Dense
from sklearn.preprocessing import MinMaxScaler
df = pd.read_csv('data/HistoricalData_1627345793457.csv')
df = df[['Date', 'Close/Last']]
print(df.head())
print(df.dtypes)
df = df.replace({'\\$': ''}, regex=True)
df = df.astype({'Close/Last': float})
df['Date'] = pd.to_datetime(df.Date, format='%m/%d/%Y')
print(df.head())
print(df.dtypes)
df.index = df['Date']
plt.plot(df['Close/Last'], label='Close Price History')
df = df.sort_index(ascending=True, axis=0)
data = pd.DataFrame(index=range(0, len(df)), columns=['Date', 'Close/Last'])
for i in range(0, len(data)):
    data['Date'][i] = df['Date'][i]
    data['Close/Last'][i] = df['Close/Last'][i]
print(data.head())
scaler = MinMaxScaler(feature_range=(0, 1))
data.index = data.Date
data.drop('Date', axis=1, inplace=True)
final_data = data.values
train_data = final_data[0:200, :]
valid_data = final_data[0:200, :]
scaled_data = scaler.fit_transform(final_data)
x_train_data, y_train_data = [], []
for i in range(60, len(train_data)):
    x_train_data.append(scaled_data[i - 60:i, 0])
    y_train_data.append(scaled_data[i, 0])
lstm_model = Sequential()
lstm_model.add(LSTM(units=50, return_sequences=True, input_shape=(np.shape(
    x_train_data)[1], 1)))
lstm_model.add(LSTM(units=50))
lstm_model.add(Dense(1))
model_data = data[len(data) - len(valid_data) - 60:].values
model_data = model_data.reshape(-1, 1)
model_data = scaler.transform(model_data)
lstm_model.compile(loss=mean_squared_error, optimizer=adam)
lstm_model.fit(x_train_data, y_train_data, epochs=1, batch_size=1, verbose=2)
X_test = []
for i in range(60, model_data.shape[0]):
    X_test.append(model_data[i - 60:i, 0])
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
predicted_stock_price = lstm_model.predict(X_test)
predicted_stock_price = scaler.inverse_transform(predicted_stock_price)
train_data = data[:200]
valid_data = data[200:]
valid_data['Predictions'] = predicted_stock_price
plt.plot(train_data['Close/Last'])
plt.plot(valid_data[['Close/Last', 'Predictions']])
plt.show()

import pandas as pd
import numpy as np

import matplotlib.pyplot as plt
from matplotlib.pylab import rcParams
from tensorflow.python.keras.losses import mean_squared_error
from tensorflow.python.keras.optimizers import adam

rcParams['figure.figsize'] = 20, 10

from keras.models import Sequential
from keras.layers import LSTM, Dropout, Dense

from sklearn.preprocessing import MinMaxScaler

# Apple Historical Data from July 25th, 2020 to July 26, 2021
df = pd.read_csv('data/HistoricalData_1627345793457.csv')

# Preprocessing to just use first two columns in csv file
df = df[['Date', 'Close/Last']]

print(df.head())

print(df.dtypes)

# Get rid of the '$' from the 'Close/Last' column
df = df.replace({'\$': ''}, regex=True)

# Convert 'Close/Last' data type to float
df = df.astype({'Close/Last': float})
df['Date'] = pd.to_datetime(df.Date, format="%m/%d/%Y")

print(df.head())
print(df.dtypes)

# Define df's index value as 'Date' Column
df.index = df['Date']

# Line chart for data we have thus far
plt.plot(df['Close/Last'], label='Close Price History')

# Data Preparation
df = df.sort_index(ascending=True, axis=0)

data = pd.DataFrame(index=range(0, len(df)), columns=['Date', 'Close/Last'])

for i in range(0, len(data)):
    data['Date'][i] = df['Date'][i]
    data['Close/Last'][i] = df['Close/Last'][i]

print(data.head())

# Min-Max Scaler
scaler = MinMaxScaler(feature_range=(0, 1))

data.index = data.Date
data.drop('Date', axis=1, inplace=True)

final_data = data.values
train_data = final_data[0:200, :]
valid_data = final_data[0:200, :]

scaled_data = scaler.fit_transform(final_data)
x_train_data, y_train_data = [], []
for i in range(60, len(train_data)):
    x_train_data.append(scaled_data[i - 60: i, 0])
    y_train_data.append(scaled_data[i, 0])

# Defining LSTM Model
lstm_model = Sequential()
lstm_model.add(LSTM(units=50, return_sequences=True, input_shape=(np.shape(x_train_data)[1], 1)))
lstm_model.add(LSTM(units=50))
lstm_model.add(Dense(1))

model_data = data[len(data) - len(valid_data) - 60:].values
model_data = model_data.reshape(-1, 1)
model_data = scaler.transform(model_data)

# Training and Testing
lstm_model.compile(loss=mean_squared_error, optimizer=adam)
lstm_model.fit(x_train_data, y_train_data, epochs=1, batch_size=1, verbose=2)

X_test = []
for i in range(60, model_data.shape[0]):
    X_test.append(model_data[i - 60:i, 0])
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))

# Prediction Function
predicted_stock_price = lstm_model.predict(X_test)
predicted_stock_price = scaler.inverse_transform(predicted_stock_price)

train_data = data[:200]
valid_data = data[200:]
valid_data['Predictions'] = predicted_stock_price
plt.plot(train_data['Close/Last'])
plt.plot(valid_data[['Close/Last', 'Predictions']])

plt.show()
