text_plain_output_1.png
from keras.layers import Dense

from keras.layers import Dense, LSTM

from keras.layers import Dropout

from keras.layers import LSTM

from keras.models import Sequential

from keras.models import Sequential

from sklearn.preprocessing import MinMaxScaler

from sklearn.preprocessing import MinMaxScaler

import keras

import numpy as np

import plotly.graph_objs as go

import yfinance as yf

import yfinance as yf
stock_name = 'AMD'
data = yf.download(stock_name, start='2020-03-26', end='2021-03-29')

from sklearn.preprocessing import MinMaxScaler
import math
import matplotlib.pyplot as plt
import keras
import pandas as pd
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout
from keras.layers import *
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split
from keras.callbacks import EarlyStopping
from keras.models import Sequential
from keras.layers import Dense, LSTM
def lstm(stock_name, data):
    data = data.filter(['Close'])
    dataset = data.values
    training_data_len = int(np.ceil(len(dataset) * 0.8))
    scaler = MinMaxScaler(feature_range=(0, 1))
    scaled_data = scaler.fit_transform(dataset)
    train_data = scaled_data[0:int(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])
    x_train, y_train = (np.array(x_train), np.array(y_train))
    x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
    model = Sequential()
    model.add(LSTM(128, return_sequences=True, input_shape=(x_train.shape[1], 1)))
    model.add(Dropout(0.35))
    model.add(LSTM(64, return_sequences=False))
    model.add(Dropout(0.3))
    model.add(Dense(25, activation='relu'))
    model.add(Dense(1))
    model.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy'])
    model.fit(x_train, y_train, batch_size=1, epochs=21)
    test_data = scaled_data[training_data_len - 60:, :]
    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])
    x_test = np.array(x_test)
    x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
    predictions = model.predict(x_test)
    predictions = scaler.inverse_transform(predictions)
    rmse = np.sqrt(np.mean((predictions - y_test) ** 2))
    train = data[:training_data_len]
    valid = data[training_data_len:]
    train_gr = np.reshape(train, (203,))
    train_gr = train_gr['Close']
    valid_gr = np.reshape(valid, (50,))
    valid_gr = valid_gr['Close']
    preds_gr = np.reshape(predictions, (50,))
    x_train = list(range(0, len(train_data)))
    x_valid = list(range(len(train_data) - 1, len(dataset)))
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=x_train, y=train_gr, mode='lines+markers', marker=dict(size=4), name='train'))
    fig.add_trace(go.Scatter(x=x_valid, y=valid_gr, mode='lines+markers', marker=dict(size=4), name='valid'))
    fig.add_trace(go.Scatter(x=x_valid, y=preds_gr, mode='lines+markers', marker=dict(size=4), name='predictions'))
    fig.update_layout(legend_orientation='h', legend=dict(x=0.5, xanchor='center'), title_text=f'{stock_name} LSTM data', title_x=0.5, xaxis_title='Timestep', yaxis_title='Stock price', margin=dict(l=0, r=0, t=30, b=0))
    data_new = yf.download(stock_name, start='2021-03-01', end='2021-04-30')
    data_new = data_new.filter(['Close'])
    dataset = data_new.values
    training_data_len = len(dataset)
    scaler = MinMaxScaler(feature_range=(0, 1))
    scaled_data = scaler.fit_transform(dataset)
    test_data = scaled_data[training_data_len - len(data_new):, :]
    x_test = []
    y_test = dataset[training_data_len:, :]
    for i in range(20, len(test_data)):
        x_test.append(test_data[i - 20:i, 0])
    x_test = np.array(x_test)
    x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
    hist_data_new = yf.download(stock_name, start='2021-04-01', end='2021-05-04')
    hist_data_new = hist_data_new.drop(['Open', 'High', 'Low', 'Adj Close', 'Volume'], axis=1)
    hist_data_new = hist_data_new['Close']
    hist_data_new = np.array(hist_data_new)
    pred_lstm = model.predict(x_test)
    pred_lstm = pred_lstm[:-1]
    pred_lstm = scaler.inverse_transform(pred_lstm)
    preds_gr = np.reshape(pred_lstm, (22,))
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=list(range(0, 21)), y=hist_data_new, mode='lines+markers', name='historical'))
    fig.add_trace(go.Scatter(x=list(range(0, 21)), y=preds_gr, mode='lines+markers', name='predictions'))
    fig.update_layout(legend_orientation='h', legend=dict(x=0.5, xanchor='center'), title_text=f'{stock_name} LSTM prediction', title_x=0.5, xaxis_title='Timestep', yaxis_title='Stock price', margin=dict(l=0, r=0, t=30, b=0))
    return (pred_lstm, rmse)

lstm_pred, lstm_rmse = lstm(stock_name, data)