# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     name: python3
# ---

# + [markdown] id="pfaDm5kvgNbf"
# # PREDICCIÓN DE LAS ACCIONES DE APPLE EMPLEANDO REDES RECURRENTES
#
#

# + id="eYlTkxfqgHir" executionInfo={"status": "ok", "timestamp": 1621294020030, "user_tz": 300, "elapsed": 1948, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}}
import cv2
import pandas as pd
import tarfile
from tqdm.notebook import tqdm
import os
import matplotlib.pyplot as plt
import numpy as np
from shutil import copyfile
import re
import glob
from sklearn.preprocessing import MinMaxScaler

# + [markdown] id="qB5z7FO1gkme"
# # Preparacion de los datos

# + id="0RlKDe2RgsF4" executionInfo={"status": "ok", "timestamp": 1621294022598, "user_tz": 300, "elapsed": 4509, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}}
data_path = "/content/drive/MyDrive/DIPLOMADO INTELIGENCIA ARTIFICIAL/TAREAS/9. RETOS/3. Prediccion de la bolsa/DATA/AAPL_2006-01-01_to_2018-01-01.csv"
DATA = pd.read_csv(data_path)

DATA['Date'] = pd.to_datetime(DATA.Date,format='%Y-%m-%d')
DATA.index = DATA['Date']
DATA = DATA.sort_index(ascending=True, axis=0)

# + colab={"base_uri": "https://localhost:8080/", "height": 450} id="dJCRIllKgsDU" executionInfo={"status": "ok", "timestamp": 1621294022599, "user_tz": 300, "elapsed": 4494, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}} outputId="449bebcf-6f5c-44ff-ea0e-9ea4b4f1f812"
DATA

# + id="Y1E4mGW3gsAy" colab={"base_uri": "https://localhost:8080/", "height": 297} executionInfo={"status": "ok", "timestamp": 1621294031578, "user_tz": 300, "elapsed": 1679, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}} outputId="4a47c26e-0aea-4e4c-cdd1-cc9af4d624e2"
DATA.describe()

# + [markdown] id="1B51C0q8F133"
# Visuazlizacion de los datos de cierre, los cuales van a ser la variable a estimar

# + colab={"base_uri": "https://localhost:8080/", "height": 505} id="12v34Ex7Fe4s" executionInfo={"status": "ok", "timestamp": 1621294033175, "user_tz": 300, "elapsed": 1579, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}} outputId="4cc0ca7e-2a06-4c5c-8406-86e2044f4826"
plt.figure(figsize=(16,8))
plt.plot(DATA['Close'][:2415], label='Conjunto de entrenamiento (Training set): 2415 puntos (80%)')
plt.plot(DATA['Close'][2415:], label='Conjunto de Validación (Validation set): 604 puntos (20%)') #248 data
plt.title("APPLE Stocks: Historia del precio la acción al cierre (Close)", size = 20)
plt.legend()
plt.show()

# + [markdown] id="0h7JY07nGQma"
# Prepararion de los vectores que mas adelante se emplearan

# + id="aZZ9UGsMgr-l" executionInfo={"status": "ok", "timestamp": 1621294035841, "user_tz": 300, "elapsed": 870, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}}
open = DATA['Open'].to_numpy().reshape((3019, 1))
close = DATA['Close'].to_numpy().reshape((3019, 1))
high = DATA['High'].to_numpy().reshape((3019, 1))
low = DATA['Low'].to_numpy().reshape((3019, 1))
volume = DATA['Volume'].to_numpy().reshape((3019, 1))

# + id="Y1Zys2xMgr8O" colab={"base_uri": "https://localhost:8080/"} executionInfo={"status": "ok", "timestamp": 1621294036436, "user_tz": 300, "elapsed": 662, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}} outputId="ae0bf091-fc5b-4835-bbe2-be7b3e12869b"
close.shape

# + [markdown] id="t-Z_uiWbI0uQ"
# Normalizado de los datos

# + id="N2-0jp7hH4Ix" executionInfo={"status": "ok", "timestamp": 1621294038433, "user_tz": 300, "elapsed": 931, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}}
scaler_open = MinMaxScaler(feature_range=(-1, 1))
scaler_close = MinMaxScaler(feature_range=(-1, 1))
scaler_high = MinMaxScaler(feature_range=(-1, 1))
scaler_low = MinMaxScaler(feature_range=(-1, 1))
scaler_volume = MinMaxScaler(feature_range=(-1, 1))

scaled_open = scaler_open.fit_transform(open)
scaled_close = scaler_close.fit_transform(close)
scaled_high = scaler_high.fit_transform(high)
scaled_low = scaler_low.fit_transform(low)
scaled_volume = scaler_volume.fit_transform(volume)

# + [markdown] id="7yxiSazFLIaS"
# ## Creacion de los datos de entrenamiento y prueba 
# ### entrada = close
# ### salida = close
# ### ventana de tiempo = 60
# ### dias = 15

# + colab={"base_uri": "https://localhost:8080/"} id="4JFhRj2NLGCi" executionInfo={"status": "ok", "timestamp": 1621294040498, "user_tz": 300, "elapsed": 829, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}} outputId="056f0908-ed2b-4476-8774-0c3092557775"
# tamaños para entrenamiento y validación
len_train = 2415 # 80%
len_valid = 604 # 20%
len_data = len_train + len_valid
# 
# Longitud de las tiras de datos para hacer las predicciones
time_step = 60
# días hasta predecir
days = 15
#
# crea datos de entrenamiento
x_train, y_train = [], []
#
for i in range(time_step ,len_train ):
    # x: bloques de "time_step" datos: 0-time_step, 1-time_step+1, 2-time_step+2, etc
    x_train.append(scaled_close[i-time_step :i,0])
    # y: el siguiente dato
    y_train.append(scaled_close[i+days,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))
y_train = np.reshape(y_train, (y_train.shape[0],1))

print("Datos de entrenamiento:")
print(x_train.shape)
print(y_train.shape)


x_test = []
y_test = []

for i in range(len_train,len_data):

    x_test.append(scaled_close[i-time_step - days:i - days,0])
    y_test.append(scaled_close[i,0])

x_test, y_test = np.array(x_test), np.array(y_test)

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


print("Datos de prueba:")
print(x_test.shape)
print(y_test.shape)



# + [markdown] id="MJ9KEo5mMF7F"
# # Creacion de los modelos

# + id="EQkW9uSVKxNI" executionInfo={"status": "ok", "timestamp": 1621294081933, "user_tz": 300, "elapsed": 553, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}}
from tensorflow.keras.layers import Dense, Input, LSTM, GRU, Flatten, Reshape, Dropout
from tensorflow.keras.models import Model
from tensorflow.keras.callbacks import ReduceLROnPlateau, ModelCheckpoint 
from tensorflow.keras.utils import plot_model

from tensorflow.keras.losses import MeanSquaredError

# + [markdown] id="DR8U8A0MMi53"
# # MODELO MK01

# + colab={"base_uri": "https://localhost:8080/", "height": 984} id="IKjDELgXMnhX" executionInfo={"status": "ok", "timestamp": 1621303081889, "user_tz": 300, "elapsed": 1411, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}} outputId="6e6bf258-38b4-4ff8-bf59-3d6beac50f30"
units = 70
input_shape = (x_train.shape[1],1)

inputs = Input(shape= input_shape, name='Inputs')
regresor_layers = inputs
dropout_rate = 0

regresor_layers = Dropout(dropout_rate, name='Dropout_1')(regresor_layers)
regresor_layers = GRU(units=units, return_sequences=True, name='GRU_1')(regresor_layers)
regresor_layers = Dropout(dropout_rate, name='Dropout_2')(regresor_layers)
regresor_layers = GRU(units=units, name='GRU_2')(regresor_layers)
regresor_layers = Dense(1, activation='tanh', name='Output')(regresor_layers)


regressor_model_mk01 = Model(inputs, regresor_layers, name ='regressor_model_mk01')

regressor_model_mk01.summary()
plot_model(regressor_model_mk01, to_file='./regressor_model_mk01.png',show_shapes=True)

# + id="IqlaM2HRMnex" executionInfo={"status": "ok", "timestamp": 1621303085164, "user_tz": 300, "elapsed": 567, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}}
regressor_model_mk01.compile(loss='mse', optimizer='adam')

# + colab={"base_uri": "https://localhost:8080/"} id="cej3P8wwMncO" executionInfo={"status": "ok", "timestamp": 1621303093814, "user_tz": 300, "elapsed": 8150, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}} outputId="7fb0c59d-e644-4641-f12a-7e8235a8a20e"
history = regressor_model_mk01.fit(x_train,y_train,validation_data=(x_test, y_test),epochs=5,batch_size=32)

# + colab={"base_uri": "https://localhost:8080/", "height": 428} id="Gz01Xn4vMnT5" executionInfo={"status": "ok", "timestamp": 1621303096811, "user_tz": 300, "elapsed": 1020, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}} outputId="8ea11250-5a99-44dc-e05b-d0e083f7c958"
plt.figure(figsize=(15,7))
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.grid()
plt.show()

# + [markdown] id="jyubCQKpndJ9"
# ### Prueba del modelo

# + id="J7p4HsKkH4EA" executionInfo={"status": "ok", "timestamp": 1621303120385, "user_tz": 300, "elapsed": 1019, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}}
prediction = regressor_model_mk01.predict(x_test)
prediction = scaler_close.inverse_transform(prediction)


# + id="lThd5v_dH4BT" executionInfo={"status": "ok", "timestamp": 1621303122621, "user_tz": 300, "elapsed": 801, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}}
def plot_prediction(real, prediccion):
    plt.figure(figsize=(15,7))
    plt.plot(real,color='red', label='Valor real de la acción')
    plt.plot(prediccion, color='blue', label='Predicción de la acción')
    plt.ylim(1.1 * np.min(prediccion)/2, 1.1 * np.max(prediccion))
    plt.xlabel('Tiempo')
    plt.ylabel('Valor de la acción')
    plt.legend()
    plt.show()


# + id="hrpclVkOgr5X" colab={"base_uri": "https://localhost:8080/", "height": 442} executionInfo={"status": "ok", "timestamp": 1621303123770, "user_tz": 300, "elapsed": 1130, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}} outputId="84bb2c36-9cce-4a24-8ba7-cef8fd4f3b47"
set_validation = close[len_data-len_valid:]
plot_prediction(scaler_close.inverse_transform(y_test) ,prediction)

# + id="hzFHp_kOqY7j" executionInfo={"status": "ok", "timestamp": 1621305158626, "user_tz": 300, "elapsed": 839, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}}
errors = scaler_close.inverse_transform(y_test) - prediction

# + colab={"base_uri": "https://localhost:8080/", "height": 444} id="0dH7r0Z4qd-R" executionInfo={"status": "ok", "timestamp": 1621302893222, "user_tz": 300, "elapsed": 1413, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}} outputId="b8fafdb6-584b-48e2-efdb-4fe827d1a0fd"
plt.figure(figsize=(15,7))
plt.hist(errors, bins=60, alpha=1, edgecolor = 'black',  linewidth=1)
plt.title('Histograma de errores')
plt.show()

# + [markdown] id="QYPrnX4OzeqP"
# ## Estimacion de intervalos de confianza
#
# Introducir drop-out al modelo ya entrenado, y ver como se comporta
#
# https://medium.com/hal24k-techblog/how-to-generate-neural-network-confidence-intervals-with-keras-e4c0b78ebbdf (Actualizado a TF 2.X)

# + id="9W_oXa40z9ND" executionInfo={"status": "ok", "timestamp": 1621302896497, "user_tz": 300, "elapsed": 718, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}}
from keras.models import Sequential
from keras import backend as K
from tensorflow.python.keras.backend import eager_learning_phase_scope


def create_dropout_predict_function(model, dropout):
    """
    Crea una funcion de keras para predecir un modelo con dropout
    model : modelo entrenado
    dropout : cantidad de dropout que se le aplicara a todas las capas
    
    Returns
    predict_with_dropout : una funcion para ahcer prediccion con dropout
    """
    
    # Load the config of the original model
    conf = model.get_config()
    # Add the specified dropout to all layers
    for layer in conf['layers']:
        # Dropout layers
        if layer["class_name"]=="Dropout":
            layer["config"]["rate"] = dropout
        # Recurrent layers with dropout
        elif "dropout" in layer["config"].keys():
            layer["config"]["dropout"] = dropout

    # Create a new model with specified dropout
    if type(model)==Sequential:
        # Sequential
        model_dropout = Sequential.from_config(conf)
    else:
        # Functional
        model_dropout = Model.from_config(conf)
    model_dropout.set_weights(model.get_weights()) 

    predict_with_dropout = K.function(model_dropout.inputs, model_dropout.outputs)
    
    return predict_with_dropout


# + id="zBzSNsmWz9Js" executionInfo={"status": "ok", "timestamp": 1621308675316, "user_tz": 300, "elapsed": 1577, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}}
model = regressor_model_mk01

dropout = 0.1 #Ajustado manualmente
num_iter = 50
num_samples = x_test.shape[0]

predict_with_dropout = create_dropout_predict_function(model, dropout)

predictions_dropout = np.zeros((num_samples, num_iter))


# Se engaña al sistema para que aplique el dropout como si estuviera entrenando
with eager_learning_phase_scope(value=1):
  for i in range(num_iter):
      predictions_dropout[:,i] = predict_with_dropout(x_test)[0].reshape(-1)


# + [markdown] id="SupcRi2bPXPS"
# Histograma de errores con el dropout de 0.1

# + colab={"base_uri": "https://localhost:8080/", "height": 444} id="ivt2iGHjPd5R" executionInfo={"status": "ok", "timestamp": 1621308676519, "user_tz": 300, "elapsed": 1777, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}} outputId="c8e20c17-7b83-43da-9f0b-f1ae378983b6"
dropout_mean_pred = np.mean(predictions_dropout, axis = 1)
dropout_mean_pred = scaler_close.inverse_transform(dropout_mean_pred.reshape(dropout_mean_pred.shape[0],1))
errors_dropout = scaler_close.inverse_transform(y_test) - dropout_mean_pred

plt.figure(figsize=(15,7))

plt.hist(errors,color = 'blue', bins=60, alpha=1, edgecolor = 'black',  linewidth=1, label='Errores del modelo base')
plt.hist(errors_dropout,color = 'red', bins=60, alpha=1, edgecolor = 'black',  linewidth=1, label='Errores del modelo con dropout')

plt.legend(loc='upper right')
plt.title('Histograma de errores')
plt.show()

# + colab={"base_uri": "https://localhost:8080/", "height": 442} id="BnlVjx9oPW3B" executionInfo={"status": "ok", "timestamp": 1621308677920, "user_tz": 300, "elapsed": 1289, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}} outputId="a78113c4-665e-443b-95b3-1aa9632d90fd"
# Se engaña al sistema para que aplique el dropout como si estuviera entrenando
with eager_learning_phase_scope(value=1):
  prediction_dropout = predict_with_dropout(x_test)[0]
  prediction_dropout = scaler_close.inverse_transform(prediction_dropout)

plt.figure(figsize=(15,7))
plt.plot(prediction,color='red', label='Prediccion normal')
plt.plot(prediction_dropout, color='blue', label='Predicción con dropout')
plt.ylim(1.1 * np.min(prediction)/2, 1.1 * np.max(prediction))
plt.xlabel('Tiempo')
plt.ylabel('Valor de la acción')
plt.legend()
plt.show()

# + [markdown] id="D1RSjbHeO8Gd"
# Se estiman los margenes de error para un intervalo de confianza determinado al 80%

# + id="N59gpKPLNfAW" executionInfo={"status": "ok", "timestamp": 1621308680082, "user_tz": 300, "elapsed": 965, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}}
intervalo_de_confianza = 0.8
lower_lim = np.quantile(predictions_dropout, 0.5-intervalo_de_confianza/2, axis=1)
upper_lim = np.quantile(predictions_dropout, 0.5+intervalo_de_confianza/2, axis=1)

lower_lim = scaler_close.inverse_transform(lower_lim.reshape(lower_lim.shape[0],1))
upper_lim = scaler_close.inverse_transform(upper_lim.reshape(upper_lim.shape[0],1))

# + colab={"base_uri": "https://localhost:8080/", "height": 458} id="eXFnFltWPORV" executionInfo={"status": "ok", "timestamp": 1621308681869, "user_tz": 300, "elapsed": 1487, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}} outputId="66772d4c-5c1f-4410-f69f-d25ab0af5800"
plt.figure(figsize=(15,7))
plt.plot(upper_lim,color='red', label='Limite inferior')
plt.plot(lower_lim, color='blue', label='Limite superior')
plt.plot(prediction, color='green', label='Prediccion')
plt.ylim(1.1 * np.min(prediction)/2, 1.1 * np.max(prediction))
plt.xlabel('Tiempo')
plt.ylabel('Valor de la acción')
plt.title('Intervalo de confianza del 80%')
plt.legend()
plt.show()

# + colab={"base_uri": "https://localhost:8080/", "height": 444} id="jsKmxwv_h9G0" executionInfo={"status": "ok", "timestamp": 1621311426750, "user_tz": 300, "elapsed": 1814, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8pIl0V_AaKknYqxYKaqtY229xAnEwl2aKBp-rAA=s64", "userId": "06929284856658854847"}} outputId="d87e8e92-9ace-4d4c-e2c6-33c5116c68ef"
plt.figure(figsize=(15,7))

intervalos_de_confianza = [0.1, 0.3, 0.5, 0.7, 0.9]
intervalos_de_confianza = list(reversed(intervalos_de_confianza))

colores = ['red', 'orange', 'yellow', 'blue', 'green']
colores = list(reversed(colores))

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

plt.plot(prediction, color='black', label='Prediccion')

for i in range(len(intervalos_de_confianza)):

  intervalo_de_confianza = intervalos_de_confianza[i]
  lower_lim = np.quantile(predictions_dropout, 0.5-intervalo_de_confianza/2, axis=1)
  upper_lim = np.quantile(predictions_dropout, 0.5+intervalo_de_confianza/2, axis=1)

  lower_lim = scaler_close.inverse_transform(lower_lim.reshape(lower_lim.shape[0],1))
  upper_lim = scaler_close.inverse_transform(upper_lim.reshape(upper_lim.shape[0],1))


  plt.fill_between(x, lower_lim.reshape(lower_lim.shape[0]), upper_lim.reshape(upper_lim.shape[0]), alpha=0.5, color=colores[i], label='Intervalo del ' + str(intervalos_de_confianza[i]*100) + '%' )
plt.title('Diferentes intervalos de confianza del modelo')
plt.legend()
plt.show()

# + id="L0qEL_28lQLn"


StarcoderdataJupyterScriptsDedupFiltered