File size: 5,897 Bytes
7e34e63
 
 
 
 
 
 
 
 
 
83155b5
7e34e63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83155b5
7e34e63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e1e010
 
 
 
 
 
 
 
 
 
7e34e63
 
 
 
 
 
 
 
 
 
 
 
83155b5
dbbd272
7e34e63
 
 
 
 
 
3911076
7e34e63
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import gradio as gr
import pandas as pd
import numpy as np
import tensorflow as tf
import yfinance as yf
from PIL import Image
import ast
from datetime import datetime, timedelta

# Cargar el modelo
modelo = tf.keras.models.load_model('best_model.keras')

# Definir constantes
img_height, img_width = 224, 224
I_min, I_max = -3.5, 3.5

# Definir listas de acciones
mineria = ['BHP', 'RIO', 'VALE', 'NEM', 'FCX', 'GOLD', 'SCCO', 'TECK', 'AA', 'AEM']
entretenimiento = ['DIS', 'NFLX', 'CMCSA', 'EA', 'TTWO', 'SONY', 'LYV', 'CNK', 'IMAX', 'AMC']
tecnologia = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'META', 'INTC', 'NVDA', 'CSCO', 'ORCL', 'IBM']
alimentacion = ['KO', 'PEP', 'MDLZ', 'TSN', 'GIS', 'K', 'CAG', 'HSY', 'SYY', 'HRL']
otros = ['JNJ', 'PG', 'WMT', 'XOM', 'JPM', 'V', 'PFE', 'HD', 'BA', 'MCD']
acciones = mineria + entretenimiento + tecnologia + alimentacion + otros

# Funci贸n para calcular fechas
def calcular_fechas(fecha_fin_str):
    fecha_fin = datetime.strptime(fecha_fin_str, '%Y-%m-%d')
    if fecha_fin.weekday() == 0:  # Lunes es 0
        fecha_inicio = fecha_fin - timedelta(days=3)
    else:
        fecha_inicio = fecha_fin - timedelta(days=1)  # Resta un d铆a en otros casos
    fecha_fin_mas_uno = fecha_fin + timedelta(days=1)
    return fecha_inicio.strftime('%Y-%m-%d'), fecha_fin_mas_uno.strftime('%Y-%m-%d')

# Funci贸n para escalar la matriz a RGB
def escalar_matriz_rgb(matriz, I_min, I_max):
    matriz_normalizada = 2 * ((matriz - I_min) / (I_max - I_min)) - 1
    rojo = (1 - matriz_normalizada.clip(max=0)) * 255
    verde = matriz_normalizada.clip(min=0) * 255
    azul = (1 - abs(matriz_normalizada)) * 255
    imagen_rgb = np.stack([rojo, verde, azul], axis=-1).astype('uint8')
    return imagen_rgb

# Funci贸n para preparar la imagen
def preparar_imagen(imagen):
    imagen = imagen.resize((img_height, img_width))
    imagen_array = np.array(imagen) / 255.0
    imagen_array = np.expand_dims(imagen_array, axis=0)
    return imagen_array

# Funci贸n para combinar las puntuaciones en una matriz de intensidades
def combinar_puntuaciones(z_vector):
    z_columna = z_vector.reshape(-1, 1)
    z_fila = z_vector.reshape(1, -1)
    matriz_intensidad = (z_columna + z_fila) / 2
    return matriz_intensidad

# Funci贸n principal para procesar y predecir
def procesar_y_predecir(fecha_fin_str):
    # Valores fijos de desviaci贸n est谩ndar y media
    desviacion_retornos = pd.Series({
        'AA': 0.033874, 'AAPL': 0.018052, 'AEM': 0.024548, 'AMC': 0.088641, 'AMZN': 0.020669,
        'BA': 0.025481, 'BHP': 0.021584, 'CAG': 0.016168, 'CMCSA': 0.015756, 'CNK': 0.034773,
        'CSCO': 0.015871, 'DIS': 0.017589, 'EA': 0.018129, 'FCX': 0.034673, 'GIS': 0.013253,
        'GOLD': 0.024993, 'GOOGL': 0.017890, 'HD': 0.015374, 'HRL': 0.014172, 'HSY': 0.013699,
        'IBM': 0.014975, 'IMAX': 0.029040, 'INTC': 0.022295, 'JNJ': 0.011410, 'JPM': 0.017179,
        'K': 0.013803, 'KO': 0.011238, 'LYV': 0.023748, 'MCD': 0.012875, 'MDLZ': 0.013368,
        'META': 0.023727, 'MSFT': 0.017148, 'NEM': 0.022646, 'NFLX': 0.027685, 'NVDA': 0.030759,
        'ORCL': 0.017283, 'PEP': 0.011764, 'PFE': 0.014615, 'PG': 0.011667, 'RIO': 0.020612,
        'SCCO': 0.022382, 'SONY': 0.018923, 'SYY': 0.018709, 'TECK': 0.035790, 'TSN': 0.017928,
        'TTWO': 0.021477, 'V': 0.015461, 'VALE': 0.030546, 'WMT': 0.013344, 'XOM': 0.017617
    })  # Coloca aqu铆 las desviaciones
    media_retornos = pd.Series({
        'AA': 0.000632, 'AAPL': 0.001083, 'AEM': 0.000843, 'AMC': 0.001134, 'AMZN': 0.001229,
        'BA': 0.000451, 'BHP': 0.000543, 'CAG': 0.000287, 'CMCSA': 0.000366, 'CNK': 0.000569,
        'CSCO': 0.000543, 'DIS': 0.000201, 'EA': 0.000629, 'FCX': 0.000933, 'GIS': 0.000337,
        'GOLD': 0.000649, 'GOOGL': 0.000899, 'HD': 0.000776, 'HRL': 0.000279, 'HSY': 0.000421,
        'IBM': 0.000449, 'IMAX': 0.000262, 'INTC': 0.000170, 'JNJ': 0.000359, 'JPM': 0.000777,
        'K': 0.000341, 'KO': 0.000398, 'LYV': 0.000882, 'MCD': 0.000679, 'MDLZ': 0.000443,
        'META': 0.001095, 'MSFT': 0.001097, 'NEM': 0.000790, 'NFLX': 0.001496, 'NVDA': 0.002764,
        'ORCL': 0.000768, 'PEP': 0.000434, 'PFE': 0.000253, 'PG': 0.000441, 'RIO': 0.000662,
        'SCCO': 0.000949, 'SONY': 0.000867, 'SYY': 0.000538, 'TECK': 0.001210, 'TSN': 0.000411,
        'TTWO': 0.000924, 'V': 0.000747, 'VALE': 0.000822, 'WMT': 0.000593, 'XOM': 0.000433
    })  # Coloca aqu铆 las medias    
    # Calcular fechas de inicio y fin
    fecha_inicio, fecha_fin_mas_uno = calcular_fechas(fecha_fin_str)

    # Descargar datos y calcular los retornos
    datos_acciones = yf.download(acciones, start=fecha_inicio, end=fecha_fin_mas_uno)['Adj Close']
    datos_acciones.fillna(media_retornos, inplace=True)
    valores = datos_acciones.pct_change().dropna().values[0]



    # Calcular puntuaciones z y generar la imagen
    puntuaciones_z = (valores - media_retornos) / desviacion_retornos
    puntuaciones_z_limited = puntuaciones_z.clip(lower=-3.5, upper=3.5)
    matriz_intensidad = combinar_puntuaciones(puntuaciones_z_limited.values)
    matriz_rgb = escalar_matriz_rgb(matriz_intensidad, I_min, I_max)
    imagen = Image.fromarray(matriz_rgb, mode='RGB')
    imagen_resized = imagen.resize((224, 224))
    imagen_procesada = preparar_imagen(imagen_resized)

    # Predecir con el modelo
    prediccion = modelo.predict(imagen_procesada)
    predicted_class = int((prediccion > 0.5).astype(int).flatten()[0])
    mensaje = "La NYSE tendr谩 ganancias en el pr贸ximo cierre." if predicted_class == 1 else "La NYSE tendr谩 p茅rdidas en el pr贸ximo cierre."
    
    return imagen_resized, mensaje

# Interfaz de Gradio
iface = gr.Interface(
    fn=procesar_y_predecir,
    inputs=gr.Textbox(label="Fecha", placeholder="Ingrese la fecha en formato AAAA-MM-DD (debe ser un d铆a h谩bil de la NYSE)"),
    outputs=[gr.Image(type="pil"), gr.Textbox(label="Predicci贸n")]
)

iface.launch()