import argparse
from helper_funcs import *
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

from TimeSeriesCrossValidation import splitTrain

from sklearn.preprocessing import MinMaxScaler, StandardScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, SimpleRNN, Dense, Dropout, Activation, RepeatVector, TimeDistributed

import config_neural_network_models as cfg_nn_models

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

from warnings import simplefilter
simplefilter(action='ignore', category=FutureWarning)


# ----------------------------------------------------------------------------------------------------
def build_neural_network_model(Recurrent_Neural_Network, n_inputs, n_days):
    model = Sequential()
    
    for idx_layer, d_layer in enumerate(Recurrent_Neural_Network):
        # Recurrent Neural Network
        if str(*d_layer) is 'SimpleRNN':
            # Is this the input layer? If so, define input_shape
            if idx_layer == 0:
                model.add(SimpleRNN(**d_layer['SimpleRNN'], input_shape=(n_inputs, 1))) 
            # Is this the last output layer? If so, set units to prediction days
            elif idx_layer == (len(Recurrent_Neural_Network)-1):
                model.add(SimpleRNN(**d_layer['SimpleRNN'], units=n_days)) 
            else:
                model.add(SimpleRNN(**d_layer['SimpleRNN']))
                
        # Long-Short Term-Memory
        elif str(*d_layer) is 'LSTM':
            # Is this the input layer? If so, define input_shape
            if idx_layer == 0:
                model.add(LSTM(**d_layer['LSTM'], input_shape=(n_inputs, 1))) 
            # Is this the last output layer? If so, set units to prediction days
            elif idx_layer == (len(Recurrent_Neural_Network)-1):
                model.add(LSTM(**d_layer['LSTM'], units=n_days)) 
            else:
                model.add(LSTM(**d_layer['LSTM']))

        # Dense (Simple Neuron)
        elif str(*d_layer) is 'Dense':
            # Is this the input layer? If so, define input_shape
            if idx_layer == 0:
                model.add(Dense(**d_layer['Dense'], input_dim=n_inputs))  
            # Is this the last output layer? If so, set units to prediction days
            elif idx_layer == (len(Recurrent_Neural_Network)-1):
                model.add(Dense(**d_layer['Dense'], units=n_days)) 
            else:
                model.add(Dense(**d_layer['Dense'])) 

        # Dropout (Regularization)
        elif str(*d_layer) is 'Dropout':
            model.add(Dropout(**d_layer['Dropout'])) 

        else:
            print(f"Incorrect neuron type: {str(*d_layer)}")
            
    return model


# -------------------------------------------------- MLP --------------------------------------------------
def mlp(l_args, s_ticker, s_interval, df_stock):
    parser = argparse.ArgumentParser(prog='mlp',
                                     description="""Multilayer Perceptron. """)

    parser.add_argument('-d', "--days", action="store", dest="n_days", type=check_positive, default=5, 
                        help='prediction days.')
    parser.add_argument('-i', "--input", action="store", dest="n_inputs", type=check_positive, default=40, 
                        help='number of days to use for prediction.')
    parser.add_argument('-e', "--epochs", action="store", dest="n_epochs", type=check_positive, default=200, 
                        help='number of training epochs.')
    parser.add_argument('-j', "--jumps", action="store", dest="n_jumps", type=check_positive, default=1, 
                        help='number of jumps in training data.')
    parser.add_argument('-p', "--pp", action="store", dest="s_preprocessing", default='normalization', 
                        choices=['normalization', 'standardization', 'none'], help='pre-processing data.')
    parser.add_argument('-o', "--optimizer", action="store", dest="s_optimizer", default='adam', 
                        choices=['adam', 'adagrad', 'adadelta', 'adamax', 'ftrl', 'nadam', 'optimizer', 'rmsprop', 'sgd'], help='optimization technique.')
    parser.add_argument('-l', "--loss", action="store", dest="s_loss", default='mae', 
                        choices=['mae', 'mape', 'mse', 'msle'], help='loss function.')

    try:
        (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)

        if l_unknown_args:
            print(f"The following args couldn't be interpreted: {l_unknown_args}\n")
            return

        # Pre-process data
        if ns_parser.s_preprocessing == 'standardization':
            scaler = StandardScaler()
            stock_train_data = scaler.fit_transform(np.array(df_stock['5. adjusted close'].values.reshape(-1, 1)))
        elif ns_parser.s_preprocessing == 'normalization':
            scaler = MinMaxScaler()
            stock_train_data = scaler.fit_transform(np.array(df_stock['5. adjusted close'].values.reshape(-1, 1)))
        else: # No pre-processing
            stock_train_data = np.array(df_stock['5. adjusted close'].values.reshape(-1, 1))

        # Split training data for the neural network
        stock_x, stock_y = splitTrain.split_train(stock_train_data, ns_parser.n_inputs, ns_parser.n_days, numJumps=ns_parser.n_jumps)
        stock_x = np.array(stock_x)
        stock_x = np.reshape(stock_x, (stock_x.shape[0], stock_x.shape[1]))
        stock_y = np.array(stock_y)
        stock_y = np.reshape(stock_y, (stock_y.shape[0], stock_y.shape[1]))

        # Build Neural Network model
        model = build_neural_network_model(cfg_nn_models.MultiLayer_Perceptron, ns_parser.n_inputs, ns_parser.n_days)
        model.compile(optimizer=ns_parser.s_optimizer, loss=ns_parser.s_loss)

        # Train our model
        model.fit(stock_x, stock_y, epochs=ns_parser.n_epochs, verbose=1);
        print("")

        print(model.summary())
        print("")

        # Prediction
        yhat = model.predict(stock_train_data[-ns_parser.n_inputs:].reshape(1, ns_parser.n_inputs), verbose=0)

        # Re-scale the data back
        if (ns_parser.s_preprocessing == 'standardization') or (ns_parser.s_preprocessing == 'normalization'): 
            y_pred_test_t = scaler.inverse_transform(yhat.tolist())
        else:
            y_pred_test_t = yhat

        l_pred_days = get_next_stock_market_days(last_stock_day=df_stock['5. adjusted close'].index[-1], n_next_days=ns_parser.n_days)
        df_pred = pd.Series(y_pred_test_t[0].tolist(), index=l_pred_days, name='Price') 

        # Plotting
        plt.plot(df_stock.index, df_stock['5. adjusted close'], lw=3)
        plt.title(f"MLP on {s_ticker} - {ns_parser.n_days} days prediction")
        plt.xlim(df_stock.index[0], get_next_stock_market_days(df_pred.index[-1], 1)[-1])
        plt.xlabel('Time')
        plt.ylabel('Share Price ($)')
        plt.grid(b=True, which='major', color='#666666', linestyle='-')
        plt.minorticks_on()
        plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2)
        plt.plot([df_stock.index[-1], df_pred.index[0]], [df_stock['5. adjusted close'].values[-1], df_pred.values[0]], lw=1, c='tab:green', linestyle='--')
        plt.plot(df_pred.index, df_pred, lw=2, c='tab:green')
        plt.axvspan(df_stock.index[-1], df_pred.index[-1], facecolor='tab:orange', alpha=0.2)
        xmin, xmax, ymin, ymax = plt.axis()
        plt.vlines(df_stock.index[-1], ymin, ymax, colors='k', linewidth=3, linestyle='--', color='k')
        plt.show()

        # Print prediction data
        print("Predicted share price:")
        df_pred = df_pred.apply(lambda x: f"{x:.2f} $")
        print(df_pred.to_string())
        print("")

    except:
        print("")


# -------------------------------------------------- RNN --------------------------------------------------
def rnn(l_args, s_ticker, s_interval, df_stock):
    parser = argparse.ArgumentParser(prog='rnn',
                                     description="""Recurrent Neural Network. """)

    parser.add_argument('-d', "--days", action="store", dest="n_days", type=check_positive, default=5, 
                        help='prediction days.')
    parser.add_argument('-i', "--input", action="store", dest="n_inputs", type=check_positive, default=40, 
                        help='number of days to use for prediction.')
    parser.add_argument('-e', "--epochs", action="store", dest="n_epochs", type=check_positive, default=200, 
                        help='number of training epochs.')
    parser.add_argument('-j', "--jumps", action="store", dest="n_jumps", type=check_positive, default=1, 
                        help='number of jumps in training data.')
    parser.add_argument('-p', "--pp", action="store", dest="s_preprocessing", default='normalization', 
                        choices=['normalization', 'standardization', 'none'], help='pre-processing data.')
    parser.add_argument('-o', "--optimizer", action="store", dest="s_optimizer", default='adam', help='optimizer technique', 
                        choices=['adam', 'adagrad', 'adadelta', 'adamax', 'ftrl', 'nadam', 'optimizer', 'rmsprop', 'sgd'])
    parser.add_argument('-l', "--loss", action="store", dest="s_loss", default='mae', 
                        choices=['mae', 'mape', 'mse', 'msle'], help='loss function.')

    try:
        (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)

        if l_unknown_args:
            print(f"The following args couldn't be interpreted: {l_unknown_args}\n")
            return

        # Pre-process data
        if ns_parser.s_preprocessing == 'standardization':
            scaler = StandardScaler()
            stock_train_data = scaler.fit_transform(np.array(df_stock['5. adjusted close'].values.reshape(-1, 1)))
        elif ns_parser.s_preprocessing == 'normalization':
            scaler = MinMaxScaler()
            stock_train_data = scaler.fit_transform(np.array(df_stock['5. adjusted close'].values.reshape(-1, 1)))
        else: # No pre-processing
            stock_train_data = np.array(df_stock['5. adjusted close'].values.reshape(-1, 1))

        # Split training data for the neural network
        stock_x, stock_y = splitTrain.split_train(stock_train_data, ns_parser.n_inputs, ns_parser.n_days, numJumps=ns_parser.n_jumps)
        stock_x = np.array(stock_x)
        stock_x = np.reshape(stock_x, (stock_x.shape[0], stock_x.shape[1], 1))
        stock_y = np.array(stock_y)
        stock_y = np.reshape(stock_y, (stock_y.shape[0], stock_y.shape[1], 1))

        # Build Neural Network model
        model = build_neural_network_model(cfg_nn_models.Recurrent_Neural_Network, ns_parser.n_inputs, ns_parser.n_days)
        model.compile(optimizer=ns_parser.s_optimizer, loss=ns_parser.s_loss)

        # Train our model
        model.fit(stock_x, stock_y, epochs=ns_parser.n_epochs, verbose=1);
        print("")

        print(model.summary())
        print("")

        # Prediction
        yhat = model.predict(stock_train_data[-ns_parser.n_inputs:].reshape(1, ns_parser.n_inputs, 1), verbose=0)

        # Re-scale the data back
        if (ns_parser.s_preprocessing == 'standardization') or (ns_parser.s_preprocessing == 'normalization'): 
            y_pred_test_t = scaler.inverse_transform(yhat.tolist())
        else:
            y_pred_test_t = yhat

        l_pred_days = get_next_stock_market_days(last_stock_day=df_stock['5. adjusted close'].index[-1], n_next_days=ns_parser.n_days)
        df_pred = pd.Series(y_pred_test_t[0].tolist(), index=l_pred_days, name='Price') 

        # Plotting
        plt.plot(df_stock.index, df_stock['5. adjusted close'], lw=3)
        plt.title(f"RNN on {s_ticker} - {ns_parser.n_days} days prediction")
        plt.xlim(df_stock.index[0], get_next_stock_market_days(df_pred.index[-1], 1)[-1])
        plt.xlabel('Time')
        plt.ylabel('Share Price ($)')
        plt.grid(b=True, which='major', color='#666666', linestyle='-')
        plt.minorticks_on()
        plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2)
        plt.plot([df_stock.index[-1], df_pred.index[0]], [df_stock['5. adjusted close'].values[-1], df_pred.values[0]], lw=1, c='tab:green', linestyle='--')
        plt.plot(df_pred.index, df_pred, lw=2, c='tab:green')
        plt.axvspan(df_stock.index[-1], df_pred.index[-1], facecolor='tab:orange', alpha=0.2)
        xmin, xmax, ymin, ymax = plt.axis()
        plt.vlines(df_stock.index[-1], ymin, ymax, colors='k', linewidth=3, linestyle='--', color='k')
        plt.show()

        # Print prediction data
        print("Predicted share price:")
        df_pred = df_pred.apply(lambda x: f"{x:.2f} $")
        print(df_pred.to_string())
        print("")

    except:
        print("")


# -------------------------------------------------- LSTM --------------------------------------------------
def lstm(l_args, s_ticker, s_interval, df_stock):
    parser = argparse.ArgumentParser(prog='lstm',
                                     description="""Long-Short Term Memory. """)

    parser.add_argument('-d', "--days", action="store", dest="n_days", type=check_positive, default=5, 
                        help='prediction days')
    parser.add_argument('-i', "--input", action="store", dest="n_inputs", type=check_positive, default=40, 
                        help='number of days to use for prediction.')
    parser.add_argument('-e', "--epochs", action="store", dest="n_epochs", type=check_positive, default=200, 
                        help='number of training epochs.')
    parser.add_argument('-j', "--jumps", action="store", dest="n_jumps", type=check_positive, default=1, 
                        help='number of jumps in training data.')
    parser.add_argument('-p', "--pp", action="store", dest="s_preprocessing", default='normalization', 
                        choices=['normalization', 'standardization', 'none'], help='pre-processing data.')
    parser.add_argument('-o', "--optimizer", action="store", dest="s_optimizer", default='adam', help='optimization technique.', 
                        choices=['adam', 'adagrad', 'adadelta', 'adamax', 'ftrl', 'nadam', 'optimizer', 'rmsprop', 'sgd'])
    parser.add_argument('-l', "--loss", action="store", dest="s_loss", default='mae', 
                        choices=['mae', 'mape', 'mse', 'msle'], help='loss function.')

    try:
        (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)

        if l_unknown_args:
            print(f"The following args couldn't be interpreted: {l_unknown_args}\n")
            return

        # Pre-process data
        if ns_parser.s_preprocessing == 'standardization':
            scaler = StandardScaler()
            stock_train_data = scaler.fit_transform(np.array(df_stock['5. adjusted close'].values.reshape(-1, 1)))
        elif ns_parser.s_preprocessing == 'normalization':
            scaler = MinMaxScaler()
            stock_train_data = scaler.fit_transform(np.array(df_stock['5. adjusted close'].values.reshape(-1, 1)))
        else: # No pre-processing
            stock_train_data = np.array(df_stock['5. adjusted close'].values.reshape(-1, 1))

        # Split training data for the neural network
        stock_x, stock_y = splitTrain.split_train(stock_train_data, ns_parser.n_inputs, ns_parser.n_days, numJumps=ns_parser.n_jumps)
        stock_x = np.array(stock_x)
        stock_x = np.reshape(stock_x, (stock_x.shape[0], stock_x.shape[1], 1))
        stock_y = np.array(stock_y)
        stock_y = np.reshape(stock_y, (stock_y.shape[0], stock_y.shape[1], 1))

        # Build Neural Network model
        model = build_neural_network_model(cfg_nn_models.Long_Short_Term_Memory, ns_parser.n_inputs, ns_parser.n_days)
        model.compile(optimizer=ns_parser.s_optimizer, loss=ns_parser.s_loss)

        # Train our model
        model.fit(stock_x, stock_y, epochs=ns_parser.n_epochs, verbose=1);
        print("")

        print(model.summary())
        print("")

        # Prediction
        yhat = model.predict(stock_train_data[-ns_parser.n_inputs:].reshape(1, ns_parser.n_inputs, 1), verbose=0)

        # Re-scale the data back
        if (ns_parser.s_preprocessing == 'standardization') or (ns_parser.s_preprocessing == 'normalization'): 
            y_pred_test_t = scaler.inverse_transform(yhat.tolist())
        else:
            y_pred_test_t = yhat

        l_pred_days = get_next_stock_market_days(last_stock_day=df_stock['5. adjusted close'].index[-1], n_next_days=ns_parser.n_days)
        df_pred = pd.Series(y_pred_test_t[0].tolist(), index=l_pred_days, name='Price') 

        # Plotting
        plt.plot(df_stock.index, df_stock['5. adjusted close'], lw=3)
        plt.title(f"LSTM on {s_ticker} - {ns_parser.n_days} days prediction")
        plt.xlim(df_stock.index[0], get_next_stock_market_days(df_pred.index[-1], 1)[-1])
        plt.xlabel('Time')
        plt.ylabel('Share Price ($)')
        plt.grid(b=True, which='major', color='#666666', linestyle='-')
        plt.minorticks_on()
        plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2)
        plt.plot([df_stock.index[-1], df_pred.index[0]], [df_stock['5. adjusted close'].values[-1], df_pred.values[0]], lw=1, c='tab:green', linestyle='--')
        plt.plot(df_pred.index, df_pred, lw=2, c='tab:green')
        plt.axvspan(df_stock.index[-1], df_pred.index[-1], facecolor='tab:orange', alpha=0.2)
        xmin, xmax, ymin, ymax = plt.axis()
        plt.vlines(df_stock.index[-1], ymin, ymax, colors='k', linewidth=3, linestyle='--', color='k')
        plt.show()

        # Print prediction data
        print("Predicted share price:")
        df_pred = df_pred.apply(lambda x: f"{x:.2f} $")
        print(df_pred.to_string())
        print("")

    except:
        print("")

matplotlib.pyplot.minorticks_on matplotlib.pyplot.plot sklearn.preprocessing.MinMaxScaler tensorflow.keras.layers.Dropout tensorflow.keras.layers.SimpleRNN numpy.reshape pandas.plotting.register_matplotlib_converters matplotlib.pyplot.axis matplotlib.pyplot.vlines tensorflow.keras.models.Sequential matplotlib.pyplot.title tensorflow.keras.layers.Dense matplotlib.pyplot.show numpy.array matplotlib.pyplot.axvspan matplotlib.pyplot.ylabel tensorflow.keras.layers.LSTM matplotlib.pyplot.grid matplotlib.pyplot.xlabel sklearn.preprocessing.StandardScaler
[(7, 'pandas.plotting.register_matplotlib_converters', 'register_matplotlib_converters', ([], {}), False, 'from pandas.plotting import register_matplotlib_converters\n'), (21, 'warnings.simplefilter', 'simplefilter', ([], {'action': '"""ignore"""', 'category': 'FutureWarning'}), False, 'from warnings import simplefilter\n'), (26, 'tensorflow.keras.models.Sequential', 'Sequential', ([], {}), False, 'from tensorflow.keras.models import Sequential\n'), (74, 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""mlp"""', 'description': '"""Multilayer Perceptron. """'}), False, 'import argparse\n'), (167, 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""rnn"""', 'description': '"""Recurrent Neural Network. """'}), False, 'import argparse\n'), (260, 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""lstm"""', 'description': '"""Long-Short Term Memory. """'}), False, 'import argparse\n'), (110, 'TimeSeriesCrossValidation.splitTrain.split_train', 'splitTrain.split_train', (['stock_train_data', 'ns_parser.n_inputs', 'ns_parser.n_days'], {'numJumps': 'ns_parser.n_jumps'}), False, 'from TimeSeriesCrossValidation import splitTrain\n'), (111, 'numpy.array', 'np.array', (['stock_x'], {}), True, 'import numpy as np\n'), (112, 'numpy.reshape', 'np.reshape', (['stock_x', '(stock_x.shape[0], stock_x.shape[1])'], {}), True, 'import numpy as np\n'), (113, 'numpy.array', 'np.array', (['stock_y'], {}), True, 'import numpy as np\n'), (114, 'numpy.reshape', 'np.reshape', (['stock_y', '(stock_y.shape[0], stock_y.shape[1])'], {}), True, 'import numpy as np\n'), (140, 'matplotlib.pyplot.plot', 'plt.plot', (['df_stock.index', "df_stock['5. adjusted close']"], {'lw': '(3)'}), True, 'import matplotlib.pyplot as plt\n'), (141, 'matplotlib.pyplot.title', 'plt.title', (['f"""MLP on {s_ticker} - {ns_parser.n_days} days prediction"""'], {}), True, 'import matplotlib.pyplot as plt\n'), (143, 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time"""'], {}), True, 'import matplotlib.pyplot as plt\n'), (144, 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Share Price ($)"""'], {}), True, 'import matplotlib.pyplot as plt\n'), (145, 'matplotlib.pyplot.grid', 'plt.grid', ([], {'b': '(True)', 'which': '"""major"""', 'color': '"""#666666"""', 'linestyle': '"""-"""'}), True, 'import matplotlib.pyplot as plt\n'), (146, 'matplotlib.pyplot.minorticks_on', 'plt.minorticks_on', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (147, 'matplotlib.pyplot.grid', 'plt.grid', ([], {'b': '(True)', 'which': '"""minor"""', 'color': '"""#999999"""', 'linestyle': '"""-"""', 'alpha': '(0.2)'}), True, 'import matplotlib.pyplot as plt\n'), (148, 'matplotlib.pyplot.plot', 'plt.plot', (['[df_stock.index[-1], df_pred.index[0]]', "[df_stock['5. adjusted close'].values[-1], df_pred.values[0]]"], {'lw': '(1)', 'c': '"""tab:green"""', 'linestyle': '"""--"""'}), True, 'import matplotlib.pyplot as plt\n'), (149, 'matplotlib.pyplot.plot', 'plt.plot', (['df_pred.index', 'df_pred'], {'lw': '(2)', 'c': '"""tab:green"""'}), True, 'import matplotlib.pyplot as plt\n'), (150, 'matplotlib.pyplot.axvspan', 'plt.axvspan', (['df_stock.index[-1]', 'df_pred.index[-1]'], {'facecolor': '"""tab:orange"""', 'alpha': '(0.2)'}), True, 'import matplotlib.pyplot as plt\n'), (151, 'matplotlib.pyplot.axis', 'plt.axis', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (152, 'matplotlib.pyplot.vlines', 'plt.vlines', (['df_stock.index[-1]', 'ymin', 'ymax'], {'colors': '"""k"""', 'linewidth': '(3)', 'linestyle': '"""--"""', 'color': '"""k"""'}), True, 'import matplotlib.pyplot as plt\n'), (153, 'matplotlib.pyplot.show', 'plt.show', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (203, 'TimeSeriesCrossValidation.splitTrain.split_train', 'splitTrain.split_train', (['stock_train_data', 'ns_parser.n_inputs', 'ns_parser.n_days'], {'numJumps': 'ns_parser.n_jumps'}), False, 'from TimeSeriesCrossValidation import splitTrain\n'), (204, 'numpy.array', 'np.array', (['stock_x'], {}), True, 'import numpy as np\n'), (205, 'numpy.reshape', 'np.reshape', (['stock_x', '(stock_x.shape[0], stock_x.shape[1], 1)'], {}), True, 'import numpy as np\n'), (206, 'numpy.array', 'np.array', (['stock_y'], {}), True, 'import numpy as np\n'), (207, 'numpy.reshape', 'np.reshape', (['stock_y', '(stock_y.shape[0], stock_y.shape[1], 1)'], {}), True, 'import numpy as np\n'), (233, 'matplotlib.pyplot.plot', 'plt.plot', (['df_stock.index', "df_stock['5. adjusted close']"], {'lw': '(3)'}), True, 'import matplotlib.pyplot as plt\n'), (234, 'matplotlib.pyplot.title', 'plt.title', (['f"""RNN on {s_ticker} - {ns_parser.n_days} days prediction"""'], {}), True, 'import matplotlib.pyplot as plt\n'), (236, 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time"""'], {}), True, 'import matplotlib.pyplot as plt\n'), (237, 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Share Price ($)"""'], {}), True, 'import matplotlib.pyplot as plt\n'), (238, 'matplotlib.pyplot.grid', 'plt.grid', ([], {'b': '(True)', 'which': '"""major"""', 'color': '"""#666666"""', 'linestyle': '"""-"""'}), True, 'import matplotlib.pyplot as plt\n'), (239, 'matplotlib.pyplot.minorticks_on', 'plt.minorticks_on', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (240, 'matplotlib.pyplot.grid', 'plt.grid', ([], {'b': '(True)', 'which': '"""minor"""', 'color': '"""#999999"""', 'linestyle': '"""-"""', 'alpha': '(0.2)'}), True, 'import matplotlib.pyplot as plt\n'), (241, 'matplotlib.pyplot.plot', 'plt.plot', (['[df_stock.index[-1], df_pred.index[0]]', "[df_stock['5. adjusted close'].values[-1], df_pred.values[0]]"], {'lw': '(1)', 'c': '"""tab:green"""', 'linestyle': '"""--"""'}), True, 'import matplotlib.pyplot as plt\n'), (242, 'matplotlib.pyplot.plot', 'plt.plot', (['df_pred.index', 'df_pred'], {'lw': '(2)', 'c': '"""tab:green"""'}), True, 'import matplotlib.pyplot as plt\n'), (243, 'matplotlib.pyplot.axvspan', 'plt.axvspan', (['df_stock.index[-1]', 'df_pred.index[-1]'], {'facecolor': '"""tab:orange"""', 'alpha': '(0.2)'}), True, 'import matplotlib.pyplot as plt\n'), (244, 'matplotlib.pyplot.axis', 'plt.axis', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (245, 'matplotlib.pyplot.vlines', 'plt.vlines', (['df_stock.index[-1]', 'ymin', 'ymax'], {'colors': '"""k"""', 'linewidth': '(3)', 'linestyle': '"""--"""', 'color': '"""k"""'}), True, 'import matplotlib.pyplot as plt\n'), (246, 'matplotlib.pyplot.show', 'plt.show', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (296, 'TimeSeriesCrossValidation.splitTrain.split_train', 'splitTrain.split_train', (['stock_train_data', 'ns_parser.n_inputs', 'ns_parser.n_days'], {'numJumps': 'ns_parser.n_jumps'}), False, 'from TimeSeriesCrossValidation import splitTrain\n'), (297, 'numpy.array', 'np.array', (['stock_x'], {}), True, 'import numpy as np\n'), (298, 'numpy.reshape', 'np.reshape', (['stock_x', '(stock_x.shape[0], stock_x.shape[1], 1)'], {}), True, 'import numpy as np\n'), (299, 'numpy.array', 'np.array', (['stock_y'], {}), True, 'import numpy as np\n'), (300, 'numpy.reshape', 'np.reshape', (['stock_y', '(stock_y.shape[0], stock_y.shape[1], 1)'], {}), True, 'import numpy as np\n'), (326, 'matplotlib.pyplot.plot', 'plt.plot', (['df_stock.index', "df_stock['5. adjusted close']"], {'lw': '(3)'}), True, 'import matplotlib.pyplot as plt\n'), (327, 'matplotlib.pyplot.title', 'plt.title', (['f"""LSTM on {s_ticker} - {ns_parser.n_days} days prediction"""'], {}), True, 'import matplotlib.pyplot as plt\n'), (329, 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time"""'], {}), True, 'import matplotlib.pyplot as plt\n'), (330, 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Share Price ($)"""'], {}), True, 'import matplotlib.pyplot as plt\n'), (331, 'matplotlib.pyplot.grid', 'plt.grid', ([], {'b': '(True)', 'which': '"""major"""', 'color': '"""#666666"""', 'linestyle': '"""-"""'}), True, 'import matplotlib.pyplot as plt\n'), (332, 'matplotlib.pyplot.minorticks_on', 'plt.minorticks_on', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (333, 'matplotlib.pyplot.grid', 'plt.grid', ([], {'b': '(True)', 'which': '"""minor"""', 'color': '"""#999999"""', 'linestyle': '"""-"""', 'alpha': '(0.2)'}), True, 'import matplotlib.pyplot as plt\n'), (334, 'matplotlib.pyplot.plot', 'plt.plot', (['[df_stock.index[-1], df_pred.index[0]]', "[df_stock['5. adjusted close'].values[-1], df_pred.values[0]]"], {'lw': '(1)', 'c': '"""tab:green"""', 'linestyle': '"""--"""'}), True, 'import matplotlib.pyplot as plt\n'), (335, 'matplotlib.pyplot.plot', 'plt.plot', (['df_pred.index', 'df_pred'], {'lw': '(2)', 'c': '"""tab:green"""'}), True, 'import matplotlib.pyplot as plt\n'), (336, 'matplotlib.pyplot.axvspan', 'plt.axvspan', (['df_stock.index[-1]', 'df_pred.index[-1]'], {'facecolor': '"""tab:orange"""', 'alpha': '(0.2)'}), True, 'import matplotlib.pyplot as plt\n'), (337, 'matplotlib.pyplot.axis', 'plt.axis', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (338, 'matplotlib.pyplot.vlines', 'plt.vlines', (['df_stock.index[-1]', 'ymin', 'ymax'], {'colors': '"""k"""', 'linewidth': '(3)', 'linestyle': '"""--"""', 'color': '"""k"""'}), True, 'import matplotlib.pyplot as plt\n'), (339, 'matplotlib.pyplot.show', 'plt.show', ([], {}), True, 'import matplotlib.pyplot as plt\n'), (101, 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), False, 'from sklearn.preprocessing import MinMaxScaler, StandardScaler\n'), (194, 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), False, 'from sklearn.preprocessing import MinMaxScaler, StandardScaler\n'), (287, 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), False, 'from sklearn.preprocessing import MinMaxScaler, StandardScaler\n'), (104, 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {}), False, 'from sklearn.preprocessing import MinMaxScaler, StandardScaler\n'), (197, 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {}), False, 'from sklearn.preprocessing import MinMaxScaler, StandardScaler\n'), (290, 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {}), False, 'from sklearn.preprocessing import MinMaxScaler, StandardScaler\n'), (33, 'tensorflow.keras.layers.SimpleRNN', 'SimpleRNN', ([], {'input_shape': '(n_inputs, 1)'}), False, 'from tensorflow.keras.layers import LSTM, SimpleRNN, Dense, Dropout, Activation, RepeatVector, TimeDistributed\n'), (36, 'tensorflow.keras.layers.SimpleRNN', 'SimpleRNN', ([], {'units': 'n_days'}), False, 'from tensorflow.keras.layers import LSTM, SimpleRNN, Dense, Dropout, Activation, RepeatVector, TimeDistributed\n'), (38, 'tensorflow.keras.layers.SimpleRNN', 'SimpleRNN', ([], {}), False, 'from tensorflow.keras.layers import LSTM, SimpleRNN, Dense, Dropout, Activation, RepeatVector, TimeDistributed\n'), (44, 'tensorflow.keras.layers.LSTM', 'LSTM', ([], {'input_shape': '(n_inputs, 1)'}), False, 'from tensorflow.keras.layers import LSTM, SimpleRNN, Dense, Dropout, Activation, RepeatVector, TimeDistributed\n'), (47, 'tensorflow.keras.layers.LSTM', 'LSTM', ([], {'units': 'n_days'}), False, 'from tensorflow.keras.layers import LSTM, SimpleRNN, Dense, Dropout, Activation, RepeatVector, TimeDistributed\n'), (49, 'tensorflow.keras.layers.LSTM', 'LSTM', ([], {}), False, 'from tensorflow.keras.layers import LSTM, SimpleRNN, Dense, Dropout, Activation, RepeatVector, TimeDistributed\n'), (55, 'tensorflow.keras.layers.Dense', 'Dense', ([], {'input_dim': 'n_inputs'}), False, 'from tensorflow.keras.layers import LSTM, SimpleRNN, Dense, Dropout, Activation, RepeatVector, TimeDistributed\n'), (64, 'tensorflow.keras.layers.Dropout', 'Dropout', ([], {}), False, 'from tensorflow.keras.layers import LSTM, SimpleRNN, Dense, Dropout, Activation, RepeatVector, TimeDistributed\n'), (58, 'tensorflow.keras.layers.Dense', 'Dense', ([], {'units': 'n_days'}), False, 'from tensorflow.keras.layers import LSTM, SimpleRNN, Dense, Dropout, Activation, RepeatVector, TimeDistributed\n'), (60, 'tensorflow.keras.layers.Dense', 'Dense', ([], {}), False, 'from tensorflow.keras.layers import LSTM, SimpleRNN, Dense, Dropout, Activation, RepeatVector, TimeDistributed\n')]