space / app.py
Quant0's picture
Update app.py
cc40fd5 verified
Raw History Blame Contribute Delete
5.28 kB
import gradio as gr
import pandas as pd
import yfinance as yf
import plotly.graph_objects as go
from datetime import datetime, timedelta
from data import *
from config import *
from processes import *
from utils import *
# -----------------------------------------------
# CONFIGURACIÓN DE LA APP CON GRADIO
# -----------------------------------------------
generar_tickers()
with gr.Blocks(title="Análisis de Correlación") as demo:
gr.Image("https://cdn.prod.website-files.com/67174dcb1d43b06a0eae317e/672bbbc7a2b88045e5661994_logo-afi.svg", show_label=False)
gr.Markdown("# Analizador de Correlación de Bitcoin")
gr.Markdown("Explora la correlación de diferentes activos con Bitcoin y sus holdings.")
with gr.Row():
input_company = gr.Dropdown(
label="Buscar por Nombre o Ticker",
choices=tickers,
value="Strategy",
allow_custom_value=True,
interactive=True
)
texto_info1 = gr.Textbox(label="Nombre Completo:", interactive=False)
# ESTE COMPONENTE ALMACENARÁ NUESTRO ESTADO (EL TICKER)
texto_info2 = gr.Textbox(label="Ticker:", interactive=True)
input_company.change(
fn=lambda texto_completo: find_company_online(texto_completo[:6]),
inputs=input_company,
outputs=[texto_info1, texto_info2]
)
# Es buena práctica ejecutar la función al cargar para rellenar los valores iniciales
demo.load(
fn=lambda texto_completo: find_company_online(texto_completo[:6]),
inputs=input_company,
outputs=[texto_info1, texto_info2]
)
with gr.Tab("Evolución de Correlación"):
output_plot = gr.Plot(label="Gráfico de Evolución")
with gr.Row():
gr.HTML("<div style='height: 2px;'></div>")
with gr.Row():
input_step = gr.Slider(minimum=1, maximum=30, value=1, step=1, label="Indica cada cuántos días se calcula la correlación")
input_window = gr.Slider(minimum=1, maximum=60, value=12, step=1, label="Ventana rolling (meses)")
with gr.Row():
gr.HTML("<div style='height: 2px;'></div>")
with gr.Row():
gr.Markdown("## Exportar:")
gr.HTML("<div style='height: 40px;'></div>")
btn_excel = gr.Button("Descargar en Excel")
output_file = gr.File(label="Archivo Excel")
output_msg = gr.Label()
gr.on(
triggers=None, # Esto hace que se ejecute al cargar
fn=plot_evolucion_correlacion_gradio,
inputs=[texto_info2, input_step, input_window],
outputs=[output_plot, output_msg]
)
btn_excel.click(
fn=exportar_correlacion,
inputs=[texto_info2, input_step, input_window],
outputs=[output_file, output_msg]
)
with gr.Tab("Stock vs BTC"):
output_iframe_stock = gr.HTML(label="Stock vs Bitcoin Chart")
gr.Markdown("#### El Multiplicador Valor de Activos Netos (MNAV) representa el valor de liquidación de una empresa. Se calcula vendiendo todos los activos, incluyendo Bitcoin, y pagando las deudas.El Ratio MNAV compara la capitalización de mercado de la empresa con este valor de liquidación.")
gr.Markdown("#### · Ratio menor a 1.0: La empresa cotiza con un descuento.")
gr.Markdown("#### · Ratio mayor a 1.0: La empresa cotiza con una prima.")
gr.Markdown("#### Este ratio ayuda a ver si una empresa está sobrevalorada o infravalorada respecto a sus activos subyacentes.")
gr.on(
triggers=None, # Esto hace que se ejecute al cargar
fn=get_iframe_stock_vs_btc,
inputs=[texto_info2],
outputs=[output_iframe_stock]
)
with gr.Tab("Holding de Bitcoin"):
output_iframe_holdings = gr.HTML(label="Bitcoin Holdings Chart")
gr.on(
triggers=None, # Esto hace que se ejecute al cargar
fn=get_iframe_holdings,
inputs=[texto_info2],
outputs=[output_iframe_holdings]
)
with gr.Tab("Exportar Resumen Holding"):
with gr.Row():
gr.Markdown("## Top Holding:")
with gr.Row():
gr.HTML(value=f"""
<div style='display: flex; justify-content: center; gap: 200px; margin-top: 40px; margin-bottom: 40px;'>
<div>{styled_ETFs.to_html()}</div>
<div>{styled_stocks.to_html()}</div>
</div>
""")
with gr.Row():
gr.Markdown("## Exportar:")
gr.HTML("<div style='height: 40px;'></div>")
btn_descargar_resumen = gr.Button("Descargar Resumen en Excel")
output_resumen_file = gr.File(label="Archivo de Resumen de Holdings")
output_resumen_msg = gr.Label()
btn_descargar_resumen.click(
fn=lambda: descargar_resumen_holding_excel("https://docs.google.com/spreadsheets/d/1Ad3bbYQAAZO6ljkaCGTGSw5aG_FQF7Lg/edit?usp=sharing"),
inputs=[],
outputs=[output_resumen_file, output_resumen_msg]
)
# Inicia la aplicación
demo.launch(share=True)