text_plain_output_2.png application_vnd.jupyter.stderr_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 pmdarima.arima import ADFTest

from pmdarima.arima import ADFTest

from pylab import rcParams

from sklearn.preprocessing import MinMaxScaler

from sklearn.preprocessing import MinMaxScaler

from statsmodels.tsa.statespace.sarimax import SARIMAX

import keras

import matplotlib.pyplot as plt

import matplotlib.pyplot as plt

import numpy as np

import numpy as np

import plotly.graph_objs as go

import pmdarima as pm

import warnings

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)

data_adf = data.drop(['Open', 'High', 'Low', 'Adj Close', 'Volume'], axis=1)
data_adf = data_adf['Close']
from pmdarima.arima import ADFTest
adf_test = ADFTest(alpha=0.05)
adf_test.should_diff(data_adf)

import os
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pmdarima as pm
plt.style.use('fivethirtyeight')
from pylab import rcParams
rcParams['figure.figsize'] = (10, 6)
from statsmodels.tsa.arima_model import ARIMA
from pmdarima.arima import ADFTest
from pmdarima.datasets import load_wineind
import random
def arima(stock_name, data):
    df_close = data['Close']
    df_log = df_close
    train_data, test_data = (df_log[3:int(len(df_log) * 0.9)], df_log[int(len(df_log) * 0.9):])
    test_values = len(df_log) * 0.01 + 1.0
    x_train = list(range(0, 224))
    x_test = list(range(224, int(len(data))))
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=x_train, y=train_data, mode='lines+markers', marker=dict(size=4), name='train'))
    fig.add_trace(go.Scatter(x=x_test, y=test_data, mode='lines+markers', marker=dict(size=4), name='test'))
    fig.update_layout(legend_orientation='h', legend=dict(x=0.5, xanchor='center'), title_text=f'{stock_name} ARIMA data', title_x=0.5, xaxis_title='Timestep', yaxis_title='Stock price', margin=dict(l=0, r=0, t=30, b=0))
    model = pm.auto_arima(df_log, start_p=0, d=None, start_q=0, max_p=5, max_d=5, max_q=5, start_P=0, D=1, start_Q=0, max_P=5, max_D=5, max_Q=5, m=7, seasonal=True, error_action='warn', trace=True, supress_warnings=True, stepwise=True, random_state=20, n_fits=50)
    model.summary()
    exo_data = data['Volume']
    exo_data = exo_data[int(len(exo_data) * 0.9):]
    preds = model.predict(n_periods=22, X=exo_data)
    preds = np.vstack(preds)
    hist_data = yf.download(stock_name, start='2021-04-01', end='2021-05-04')
    hist_data = hist_data.drop(['Open', 'High', 'Low', 'Adj Close', 'Volume'], axis=1)
    hist_data = hist_data['Close']
    hist_data = np.array(hist_data)
    rmse = np.sqrt(np.mean((preds - hist_data) ** 2))
    preds_gr = np.reshape(preds, (22,))
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=list(range(0, 21)), y=hist_data, 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} ARIMA prediction', title_x=0.5, xaxis_title='Timestep', yaxis_title='Stock price', margin=dict(l=0, r=0, t=30, b=0))
    return (preds, rmse)

from statsmodels.tsa.statespace.sarimax import SARIMAX
data3 = data['Close']
train3_data, test3_data = (data3[3:int(len(data3) * 0.9)], data3[int(len(data3) * 0.9):])
x_train = list(range(0, 224))
x_test = list(range(224, int(len(data3))))
exo_data = data['Volume']
exo_data = exo_data[int(len(exo_data) * 0.9):]
fig = go.Figure()
fig.add_trace(go.Scatter(x=x_train, y=train3_data, mode='lines+markers', marker=dict(size=4), name='train'))
fig.add_trace(go.Scatter(x=x_test, y=test3_data, mode='lines+markers', marker=dict(size=4), name='test'))
fig.update_layout(legend_orientation='h', legend=dict(x=0.5, xanchor='center'), title_text=f'{stock_name} SARIMAX data', title_x=0.5, xaxis_title='Timestep', yaxis_title='Stock price', margin=dict(l=0, r=0, t=30, b=0))
fig.show()
model = SARIMAX(train3_data, order=(3, 1, 2))
arima_model = model.fit(X=exo_data, disp=-1)
print(arima_model.summary())
preds3 = arima_model.predict(n_periods=22, alpha=0.05)
preds3 = np.vstack(preds3)
preds3 = preds3[-22:]
hist_data = yf.download(stock_name, start='2021-04-01', end='2021-05-04')
hist_data = hist_data.drop(['Open', 'High', 'Low', 'Adj Close', 'Volume'], axis=1)
hist_data = hist_data['Close']
hist_data = np.array(hist_data)
rmse = np.sqrt(np.mean((preds3 - hist_data) ** 2))
print(f'RMSE SARIMAX: {rmse}')
preds_gr = np.reshape(preds3, (22,))
fig = go.Figure()
fig.add_trace(go.Scatter(x=list(range(0, 21)), y=hist_data, 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} SARIMAX prediction', title_x=0.5, xaxis_title='Timestep', yaxis_title='Stock price', margin=dict(l=0, r=0, t=30, b=0))
fig.show()