Delete procesos.py
Browse files- procesos.py +0 -122
procesos.py
DELETED
|
@@ -1,122 +0,0 @@
|
|
| 1 |
-
# -*- coding: utf-8 -*-
|
| 2 |
-
# Módulo de procesamiento y análisis de datos
|
| 3 |
-
|
| 4 |
-
import pandas as pd
|
| 5 |
-
import numpy as np
|
| 6 |
-
import yfinance as yf
|
| 7 |
-
from datetime import datetime, timedelta
|
| 8 |
-
import gdown
|
| 9 |
-
import shutil
|
| 10 |
-
import os
|
| 11 |
-
|
| 12 |
-
from data import all_historical_data
|
| 13 |
-
from config import DEFAULT_TEMPLATE_URL
|
| 14 |
-
from utils import limpiar_texto, expand_money, extract_file_id, descargar_tabla_web
|
| 15 |
-
|
| 16 |
-
def evolucion_correlacion(ticker_company, step, ticker_btc="BTC-USD", window_months=12):
|
| 17 |
-
"""Calcula la evolución de la correlación entre el precio de las acciones de una empresa y Bitcoin."""
|
| 18 |
-
end_date = datetime.now()
|
| 19 |
-
start_date = end_date - timedelta(days=10 * 365)
|
| 20 |
-
|
| 21 |
-
if ticker_company not in all_historical_data:
|
| 22 |
-
data = yf.download(ticker_company, start=start_date, end=end_date)
|
| 23 |
-
if not data.empty:
|
| 24 |
-
all_historical_data[ticker_company] = data
|
| 25 |
-
else:
|
| 26 |
-
return None
|
| 27 |
-
|
| 28 |
-
if ticker_btc not in all_historical_data:
|
| 29 |
-
data = yf.download(ticker_btc, start=start_date, end=end_date)
|
| 30 |
-
if not data.empty:
|
| 31 |
-
all_historical_data[ticker_btc] = data
|
| 32 |
-
else:
|
| 33 |
-
return None
|
| 34 |
-
|
| 35 |
-
company_data = all_historical_data.get(ticker_company)
|
| 36 |
-
btc_data = all_historical_data.get(ticker_btc)
|
| 37 |
-
|
| 38 |
-
if company_data.empty or btc_data.empty:
|
| 39 |
-
return None
|
| 40 |
-
|
| 41 |
-
company_returns = company_data['Close'].pct_change().dropna()
|
| 42 |
-
btc_returns = btc_data['Close'].pct_change().dropna()
|
| 43 |
-
|
| 44 |
-
window_days = window_months * 30
|
| 45 |
-
if step == 0:
|
| 46 |
-
corr = company_returns.rolling(window=f"{window_days}D").corr(btc_returns).iloc[-1]
|
| 47 |
-
return pd.Series([corr], index=[end_date])
|
| 48 |
-
else:
|
| 49 |
-
corr_series = company_returns.rolling(window=f"{window_days}D").corr(btc_returns).dropna()
|
| 50 |
-
return corr_series.iloc[9::step]
|
| 51 |
-
|
| 52 |
-
def exportar_correlacion(ticker_company, step, window_months):
|
| 53 |
-
"""Exporta la serie de correlación a un archivo Excel."""
|
| 54 |
-
try:
|
| 55 |
-
serie = evolucion_correlacion(ticker_company, step, window_months)
|
| 56 |
-
if serie is not None and not serie.empty:
|
| 57 |
-
nombre_archivo = f"{ticker_company}_evolucion_correlacion.xlsx"
|
| 58 |
-
serie.to_excel(nombre_archivo)
|
| 59 |
-
return nombre_archivo, "Archivo Excel generado con éxito."
|
| 60 |
-
else:
|
| 61 |
-
return None, "No se pudieron generar los datos para exportar."
|
| 62 |
-
except Exception as e:
|
| 63 |
-
return None, f"Error al exportar: {e}"
|
| 64 |
-
|
| 65 |
-
def descargar_resumen_holding_excel(template_url=DEFAULT_TEMPLATE_URL):
|
| 66 |
-
"""Descarga los datos de holding de BTC para stocks y ETFs, calcula correlaciones y exporta a Excel."""
|
| 67 |
-
try:
|
| 68 |
-
file_id = extract_file_id(template_url)
|
| 69 |
-
if not file_id:
|
| 70 |
-
return None, "Error: No se pudo extraer el ID del archivo de la URL."
|
| 71 |
-
|
| 72 |
-
local_template_path = 'plantilla_temporal.xlsx'
|
| 73 |
-
gdown.download(id=file_id, output=local_template_path, quiet=False)
|
| 74 |
-
|
| 75 |
-
df_stocks = descargar_tabla_web("https://bitcointreasuries.net/", indice_tabla=3)
|
| 76 |
-
df_etfs = descargar_tabla_web("https://bitcointreasuries.net/etfs-and-exchanges", indice_tabla=3)
|
| 77 |
-
|
| 78 |
-
if df_stocks is None and df_etfs is None:
|
| 79 |
-
return None, "Error: No se pudieron descargar los datos de holding."
|
| 80 |
-
|
| 81 |
-
resumen = {}
|
| 82 |
-
|
| 83 |
-
if df_stocks is not None:
|
| 84 |
-
df = df_stocks[[2, 3, 4, 5, 12]].copy()
|
| 85 |
-
df.columns = ['Name', 'Bitcoin', 'BTC in USD', 'Marketcap', '% Total BTC 21M']
|
| 86 |
-
df[['Name', 'Ticker']] = df['Name'].apply(limpiar_texto).str.rsplit(' ', n=1, expand=True)
|
| 87 |
-
df['BTC in USD'] = df['BTC in USD'].apply(expand_money)
|
| 88 |
-
df['Marketcap'] = df['Marketcap'].apply(expand_money)
|
| 89 |
-
df['Ratio Holding/Mcap'] = df['BTC in USD'] / df['Marketcap']
|
| 90 |
-
df.set_index('Ticker', inplace=True)
|
| 91 |
-
|
| 92 |
-
corrs = []
|
| 93 |
-
for ticker in df.index:
|
| 94 |
-
try:
|
| 95 |
-
corr = evolucion_correlacion(ticker, step=0, window_months=12).iloc[0]
|
| 96 |
-
corrs.append(corr)
|
| 97 |
-
except:
|
| 98 |
-
corrs.append(np.nan)
|
| 99 |
-
df['Correlación con BTC (12 meses)'] = corrs
|
| 100 |
-
resumen['Stocks'] = df
|
| 101 |
-
|
| 102 |
-
if df_etfs is not None:
|
| 103 |
-
df = df_etfs[[2, 3, 4, 5]].copy()
|
| 104 |
-
df.columns = ['Name', 'Bitcoin', 'BTC in USD', '% Total BTC 21M']
|
| 105 |
-
df[['Name', 'Ticker']] = df['Name'].apply(limpiar_texto).str.rsplit(' ', n=1, expand=True)
|
| 106 |
-
df['Ticker'].fillna(df['Name'], inplace=True)
|
| 107 |
-
df['BTC in USD'] = df['BTC in USD'].apply(expand_money)
|
| 108 |
-
df['Bitcoin'] = df['Bitcoin'].apply(limpiar_texto).apply(expand_money)
|
| 109 |
-
df.set_index('Ticker', inplace=True)
|
| 110 |
-
resumen['ETFs'] = df
|
| 111 |
-
|
| 112 |
-
nuevo_archivo_path = 'resumen_datos_holding.xlsx'
|
| 113 |
-
shutil.copyfile(local_template_path, nuevo_archivo_path)
|
| 114 |
-
|
| 115 |
-
with pd.ExcelWriter(nuevo_archivo_path, engine='openpyxl', mode='a', if_sheet_exists='replace') as writer:
|
| 116 |
-
for sheet, df in resumen.items():
|
| 117 |
-
df.to_excel(writer, sheet_name=sheet)
|
| 118 |
-
|
| 119 |
-
os.remove(local_template_path)
|
| 120 |
-
return nuevo_archivo_path, "Archivo Excel generado con éxito."
|
| 121 |
-
except Exception as e:
|
| 122 |
-
return None, f"Error al exportar: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|