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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ============================================================
|
| 2 |
+
# exports.py — Exportación a Excel (series y resúmenes)
|
| 3 |
+
# ------------------------------------------------------------
|
| 4 |
+
# NOTA PARA AUDITORÍA:
|
| 5 |
+
# - Este módulo encapsula las exportaciones a Excel que antes estaban
|
| 6 |
+
# en la app. No ejecuta nada al importarlo (sin efectos secundarios).
|
| 7 |
+
# - Mantiene la lógica y los textos de estado que usabas en app1 6.py.
|
| 8 |
+
# - Depende de:
|
| 9 |
+
# * analytics.evolucion_correlacion (cálculo de correlación)
|
| 10 |
+
# * scraping.descargar_tabla_web, limpiar_texto, expand_money
|
| 11 |
+
# * yfinance (para detectar disponibilidad de opciones)
|
| 12 |
+
# * gdown/openpyxl/pandas (para la exportación a Excel)
|
| 13 |
+
# ============================================================
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
import re
|
| 19 |
+
import shutil
|
| 20 |
+
from typing import Optional, Tuple, Dict, List
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
import pandas as pd
|
| 24 |
+
import yfinance as yf
|
| 25 |
+
|
| 26 |
+
from analytics import evolucion_correlacion
|
| 27 |
+
from scraping import descargar_tabla_web, limpiar_texto, expand_money
|
| 28 |
+
|
| 29 |
+
# gdown se usa para descargar la plantilla de Google Drive
|
| 30 |
+
import gdown
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# ============================================================
|
| 34 |
+
# Utilidad: extraer ID de archivo de una URL de Google Drive
|
| 35 |
+
# ============================================================
|
| 36 |
+
def extract_file_id(url: str) -> Optional[str]:
|
| 37 |
+
"""
|
| 38 |
+
Extrae el ID del archivo de una URL de Google Drive.
|
| 39 |
+
|
| 40 |
+
Acepta formatos habituales:
|
| 41 |
+
- https://drive.google.com/file/d/<ID>/view?usp=sharing
|
| 42 |
+
- https://docs.google.com/spreadsheets/d/<ID>/edit
|
| 43 |
+
- https://drive.google.com/open?id=<ID>
|
| 44 |
+
|
| 45 |
+
Devuelve:
|
| 46 |
+
- str con el ID si se reconoce; en caso contrario, None.
|
| 47 |
+
"""
|
| 48 |
+
if not url:
|
| 49 |
+
return None
|
| 50 |
+
|
| 51 |
+
# /d/<ID>/
|
| 52 |
+
m = re.search(r"/d/([a-zA-Z0-9_-]+)", url)
|
| 53 |
+
if m:
|
| 54 |
+
return m.group(1)
|
| 55 |
+
|
| 56 |
+
# ?id=<ID>
|
| 57 |
+
m = re.search(r"[?&]id=([a-zA-Z0-9_-]+)", url)
|
| 58 |
+
if m:
|
| 59 |
+
return m.group(1)
|
| 60 |
+
|
| 61 |
+
return None
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# ============================================================
|
| 65 |
+
# Exportar: Serie de correlación a Excel
|
| 66 |
+
# ============================================================
|
| 67 |
+
def exportar_correlacion(
|
| 68 |
+
ticker_company: str, step: int, window_months: int
|
| 69 |
+
) -> Tuple[Optional[str], str]:
|
| 70 |
+
"""
|
| 71 |
+
Exporta a Excel la serie de correlación rolling entre `ticker_company`
|
| 72 |
+
y BTC-USD (o el valor por defecto que usa `evolucion_correlacion`).
|
| 73 |
+
|
| 74 |
+
Parámetros
|
| 75 |
+
----------
|
| 76 |
+
ticker_company : str
|
| 77 |
+
Ticker de la empresa/ETF (p. ej. 'MSTR').
|
| 78 |
+
step : int
|
| 79 |
+
Salto de muestreo en días (si 0, devuelve solo el último valor).
|
| 80 |
+
window_months : int
|
| 81 |
+
Ventana rolling en meses (p. ej., 12).
|
| 82 |
+
|
| 83 |
+
Devuelve
|
| 84 |
+
--------
|
| 85 |
+
(str | None, str)
|
| 86 |
+
Ruta del archivo generado y un mensaje de estado.
|
| 87 |
+
"""
|
| 88 |
+
try:
|
| 89 |
+
serie = evolucion_correlacion(ticker_company, step, window_months=window_months)
|
| 90 |
+
if serie is not None and not serie.empty:
|
| 91 |
+
nombre_archivo = f"{ticker_company}_evolucion_correlacion.xlsx"
|
| 92 |
+
serie.to_excel(nombre_archivo)
|
| 93 |
+
return nombre_archivo, "Archivo Excel generado con éxito."
|
| 94 |
+
else:
|
| 95 |
+
return None, "No se pudieron generar los datos para exportar."
|
| 96 |
+
except Exception as e:
|
| 97 |
+
return None, f"Error al exportar: {e}"
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
# ============================================================
|
| 101 |
+
# Exportar: Resumen holdings (Stocks / ETFs) a partir de plantilla
|
| 102 |
+
# ============================================================
|
| 103 |
+
def descargar_resumen_holding_excel(template_url: str) -> Tuple[Optional[str], str]:
|
| 104 |
+
"""
|
| 105 |
+
Descarga una plantilla de Google Drive y genera un Excel con:
|
| 106 |
+
- Hoja 'Stocks' (datos de bitcointreasuries.net, correlación 12m, opciones...)
|
| 107 |
+
- Hoja 'ETFs' (datos de bitcointreasuries.net, opciones...)
|
| 108 |
+
|
| 109 |
+
Lógica respetando tu implementación original:
|
| 110 |
+
1) Descargar tabla de stocks (índice 3) y ETFs (índice 3) con ScraperAPI.
|
| 111 |
+
2) Limpiar columnas, extraer Name y Ticker.
|
| 112 |
+
3) Convertir 'BTC in USD' y 'Marketcap' a float (expand_money).
|
| 113 |
+
4) Calcular ratio Holding/Mcap (stocks).
|
| 114 |
+
5) Calcular correlación 12m para cada ticker (stocks).
|
| 115 |
+
6) Detectar disponibilidad de opciones en yfinance (ambas hojas).
|
| 116 |
+
7) Escribir hojas en un Excel a partir de una plantilla descargada con gdown.
|
| 117 |
+
|
| 118 |
+
Parámetros
|
| 119 |
+
----------
|
| 120 |
+
template_url : str
|
| 121 |
+
URL de la plantilla en Google Drive (formato compartible).
|
| 122 |
+
|
| 123 |
+
Devuelve
|
| 124 |
+
--------
|
| 125 |
+
(str | None, str)
|
| 126 |
+
Ruta del Excel generado y mensaje de estado.
|
| 127 |
+
"""
|
| 128 |
+
try:
|
| 129 |
+
# --------------------------------------------------------
|
| 130 |
+
# 1) Descargar plantilla de Google Drive
|
| 131 |
+
# --------------------------------------------------------
|
| 132 |
+
file_id = extract_file_id(template_url)
|
| 133 |
+
if not file_id:
|
| 134 |
+
return None, "Error: No se pudo extraer el ID del archivo de la URL de Google Drive."
|
| 135 |
+
|
| 136 |
+
local_template_path = "plantilla_temporal.xlsx"
|
| 137 |
+
try:
|
| 138 |
+
gdown.download(id=file_id, output=local_template_path, quiet=False)
|
| 139 |
+
except Exception as e:
|
| 140 |
+
return None, f"Error al descargar la plantilla desde Google Drive: {e}"
|
| 141 |
+
|
| 142 |
+
# --------------------------------------------------------
|
| 143 |
+
# 2) Descargar y construir DataFrames desde bitcointreasuries
|
| 144 |
+
# --------------------------------------------------------
|
| 145 |
+
url_stocks = "https://bitcointreasuries.net/"
|
| 146 |
+
url_etfs = "https://bitcointreasuries.net/etfs-and-exchanges"
|
| 147 |
+
|
| 148 |
+
df_stocks_raw = descargar_tabla_web(url_stocks, indice_tabla=3)
|
| 149 |
+
df_etfs_raw = descargar_tabla_web(url_etfs, indice_tabla=3)
|
| 150 |
+
|
| 151 |
+
if df_stocks_raw is None and df_etfs_raw is None:
|
| 152 |
+
# Limpiar plantilla temporal antes de salir
|
| 153 |
+
try:
|
| 154 |
+
os.remove(local_template_path)
|
| 155 |
+
except Exception:
|
| 156 |
+
pass
|
| 157 |
+
return None, "Error: No se pudieron descargar los datos de holding."
|
| 158 |
+
|
| 159 |
+
# --------------------------------------------------------
|
| 160 |
+
# 3) Procesar STOCKS
|
| 161 |
+
# --------------------------------------------------------
|
| 162 |
+
if df_stocks_raw is not None:
|
| 163 |
+
# Selección de columnas según tu código original:
|
| 164 |
+
# [2,3,4,5,12] → 'Name','Bitcoin','BTC in USD','Marketcap','% Total BTC 21M'
|
| 165 |
+
df_descargado_stocks = df_stocks_raw[[2, 3, 4, 5, 12]].copy()
|
| 166 |
+
df_descargado_stocks.columns = ['Name', 'Bitcoin', 'BTC in USD', 'Marketcap', '% Total BTC 21M']
|
| 167 |
+
|
| 168 |
+
# Limpiar y separar Name y Ticker (por el último espacio)
|
| 169 |
+
df_descargado_stocks[['Name', 'Ticker']] = (
|
| 170 |
+
df_descargado_stocks['Name'].apply(limpiar_texto).str.rsplit(' ', n=1, expand=True)
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
# Limpiezas y conversiones monetarias
|
| 174 |
+
df_descargado_stocks['Bitcoin'] = df_descargado_stocks['Bitcoin'].apply(limpiar_texto)
|
| 175 |
+
df_descargado_stocks['Marketcap'] = df_descargado_stocks['Marketcap'].apply(limpiar_texto)
|
| 176 |
+
|
| 177 |
+
df_descargado_stocks['BTC in USD'] = df_descargado_stocks['BTC in USD'].apply(expand_money)
|
| 178 |
+
df_descargado_stocks['Marketcap'] = df_descargado_stocks['Marketcap'].apply(expand_money)
|
| 179 |
+
|
| 180 |
+
# Ratio holding/mcap (puede dar NaN si faltan datos)
|
| 181 |
+
df_descargado_stocks['Ratio Holding/Mcap'] = (
|
| 182 |
+
df_descargado_stocks['BTC in USD'] / df_descargado_stocks['Marketcap']
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
# Correlación 12 meses por ticker (manteniendo tu step=0)
|
| 186 |
+
corrs: List[float] = []
|
| 187 |
+
for stock in df_descargado_stocks['Ticker']:
|
| 188 |
+
try:
|
| 189 |
+
serie = evolucion_correlacion(stock, step=0, window_months=12)
|
| 190 |
+
corr_value = float(serie.iloc[0]) if (serie is not None and not serie.empty) else np.nan
|
| 191 |
+
corrs.append(corr_value)
|
| 192 |
+
except Exception:
|
| 193 |
+
corrs.append(np.nan)
|
| 194 |
+
|
| 195 |
+
df_descargado_stocks['Correlación con BTC (12 meses)'] = pd.Series(corrs)
|
| 196 |
+
df_descargado_stocks.set_index('Ticker', inplace=True)
|
| 197 |
+
else:
|
| 198 |
+
df_descargado_stocks = pd.DataFrame()
|
| 199 |
+
|
| 200 |
+
# --------------------------------------------------------
|
| 201 |
+
# 4) Procesar ETFs
|
| 202 |
+
# --------------------------------------------------------
|
| 203 |
+
if df_etfs_raw is not None:
|
| 204 |
+
# Selección de columnas según tu código original:
|
| 205 |
+
# [2,3,4,5] → 'Name','Bitcoin','BTC in USD','% Total BTC 21M'
|
| 206 |
+
df_descargado_ETFs = df_etfs_raw[[2, 3, 4, 5]].copy()
|
| 207 |
+
df_descargado_ETFs.columns = ['Name', 'Bitcoin', 'BTC in USD', '% Total BTC 21M']
|
| 208 |
+
|
| 209 |
+
df_descargado_ETFs[['Name', 'Ticker']] = (
|
| 210 |
+
df_descargado_ETFs['Name'].apply(limpiar_texto).str.rsplit(' ', n=1, expand=True)
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
# Si no hay ticker separado, usa Name como fallback (tal cual hacías)
|
| 214 |
+
df_descargado_ETFs['Ticker'].fillna(df_descargado_ETFs['Name'], inplace=True)
|
| 215 |
+
|
| 216 |
+
df_descargado_ETFs['BTC in USD'] = df_descargado_ETFs['BTC in USD'].apply(expand_money)
|
| 217 |
+
df_descargado_ETFs['Bitcoin'] = df_descargado_ETFs['Bitcoin'].apply(limpiar_texto).apply(expand_money)
|
| 218 |
+
|
| 219 |
+
df_descargado_ETFs.set_index('Ticker', inplace=True)
|
| 220 |
+
else:
|
| 221 |
+
df_descargado_ETFs = pd.DataFrame()
|
| 222 |
+
|
| 223 |
+
# --------------------------------------------------------
|
| 224 |
+
# 5) Flag 'Options' (si yfinance expone cadena de opciones)
|
| 225 |
+
# --------------------------------------------------------
|
| 226 |
+
tickers: List[str] = []
|
| 227 |
+
if not df_descargado_stocks.empty:
|
| 228 |
+
tickers.extend(df_descargado_stocks.index.tolist())
|
| 229 |
+
if not df_descargado_ETFs.empty:
|
| 230 |
+
tickers.extend(df_descargado_ETFs.index.tolist())
|
| 231 |
+
|
| 232 |
+
options_bool: Dict[str, bool] = {}
|
| 233 |
+
for t in tickers:
|
| 234 |
+
if t is None:
|
| 235 |
+
continue
|
| 236 |
+
try:
|
| 237 |
+
options_bool[t] = False if not yf.Ticker(t).options else True
|
| 238 |
+
except Exception:
|
| 239 |
+
options_bool[t] = False
|
| 240 |
+
|
| 241 |
+
options_series = pd.Series(options_bool)
|
| 242 |
+
|
| 243 |
+
if not df_descargado_stocks.empty:
|
| 244 |
+
df_descargado_stocks['Options'] = options_series
|
| 245 |
+
if not df_descargado_ETFs.empty:
|
| 246 |
+
df_descargado_ETFs['Options'] = options_series
|
| 247 |
+
|
| 248 |
+
# --------------------------------------------------------
|
| 249 |
+
# 6) Escribir el Excel final a partir de la plantilla
|
| 250 |
+
# --------------------------------------------------------
|
| 251 |
+
nuevo_archivo_path = "resumen_datos_holding.xlsx"
|
| 252 |
+
try:
|
| 253 |
+
shutil.copyfile(local_template_path, nuevo_archivo_path)
|
| 254 |
+
except FileNotFoundError:
|
| 255 |
+
# Limpiar plantilla temporal antes de salir
|
| 256 |
+
try:
|
| 257 |
+
os.remove(local_template_path)
|
| 258 |
+
except Exception:
|
| 259 |
+
pass
|
| 260 |
+
return None, f"Error: No se encontró la plantilla en la ruta: {local_template_path}"
|
| 261 |
+
|
| 262 |
+
# Escribir hojas (reemplaza si existen)
|
| 263 |
+
with pd.ExcelWriter(nuevo_archivo_path, engine="openpyxl", mode="a", if_sheet_exists="replace") as writer:
|
| 264 |
+
if not df_descargado_stocks.empty:
|
| 265 |
+
df_descargado_stocks.to_excel(writer, sheet_name="Stocks", index=True)
|
| 266 |
+
if not df_descargado_ETFs.empty:
|
| 267 |
+
df_descargado_ETFs.to_excel(writer, sheet_name="ETFs", index=True)
|
| 268 |
+
|
| 269 |
+
# Eliminar la plantilla temporal para limpiar entorno
|
| 270 |
+
try:
|
| 271 |
+
os.remove(local_template_path)
|
| 272 |
+
except Exception:
|
| 273 |
+
pass
|
| 274 |
+
return nuevo_archivo_path, "Archivo Excel generado con éxito."
|
| 275 |
+
|
| 276 |
+
except Exception as e:
|
| 277 |
+
# En caso de error no previsto
|
| 278 |
+
return None, f"Error al exportar: {e}"
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
__all__ = [
|
| 282 |
+
"exportar_correlacion",
|
| 283 |
+
"descargar_resumen_holding_excel",
|
| 284 |
+
"extract_file_id",
|
| 285 |
+
]
|