Quant0 commited on
Commit
a840e82
·
verified ·
1 Parent(s): 5aa014a

Create data_sources.py

Browse files
Files changed (1) hide show
  1. data_sources.py +281 -0
data_sources.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # data_sources.py — Origen de datos y caché en memoria
3
+ # ------------------------------------------------------------
4
+ # NOTA PARA AUDITORÍA:
5
+ # - Este módulo centraliza la obtención y el almacenamiento en caché
6
+ # de series históricas (p. ej., precios de cierre diarios con yfinance
7
+ # y BTC a 1h desde CryptoCompare), sin efectos secundarios al importar.
8
+ # - Expone:
9
+ # * all_historical_data: dict[str, pandas.DataFrame]
10
+ # * get_data(ticker, start, end): descarga con yfinance si falta en caché
11
+ # * load_btc_hourly_cryptocompare_to_cache(...): descarga BTC 1h desde
12
+ # CryptoCompare y lo transforma a cierre de las 16:00 (NY), como en tu
13
+ # código original, guardando además CSV local.
14
+ # * save_cache_snapshot(...): guarda a CSVs el contenido del caché.
15
+ # - Las API keys se leen de variables de entorno:
16
+ # * CRYPTOCOMPARE_API_KEY
17
+ # * TIMEZONE_TARGET (por defecto: 'America/New_York')
18
+ # ============================================================
19
+
20
+ from __future__ import annotations
21
+
22
+ import os
23
+ import time
24
+ from datetime import datetime, timedelta
25
+ from typing import Dict, Optional
26
+
27
+ import pandas as pd
28
+ import requests
29
+ import yfinance as yf
30
+
31
+
32
+ # ------------------------------------------------------------
33
+ # Caché global de históricos (compartido con analytics.py)
34
+ # ------------------------------------------------------------
35
+ # Clave: ticker (str), Valor: DataFrame con índice de fechas.
36
+ all_historical_data: Dict[str, pd.DataFrame] = {}
37
+
38
+
39
+ # ------------------------------------------------------------
40
+ # Configuración (entorno)
41
+ # ------------------------------------------------------------
42
+ CRYPTOCOMPARE_API_KEY = os.getenv("CRYPTOCOMPARE_API_KEY", "TU_API_KEY_DE_CRYPTOCOMPARE") # opcional
43
+ TIMEZONE_TARGET = os.getenv("TIMEZONE_TARGET", "America/New_York") # para conversión de BTC 1h
44
+ CRYPTOCOMPARE_BASE_URL = "https://min-api.cryptocompare.com/data/v2/histohour"
45
+
46
+
47
+ # ============================================================
48
+ # Utilidad: descarga condicional con yfinance y guarda en caché
49
+ # ============================================================
50
+ def get_data(
51
+ ticker: str,
52
+ start: Optional[datetime] = None,
53
+ end: Optional[datetime] = None,
54
+ silent: bool = False,
55
+ ) -> pd.DataFrame:
56
+ """
57
+ Obtiene datos de un ticker desde el caché; si no existen, descarga con yfinance.
58
+
59
+ Parámetros
60
+ ----------
61
+ ticker : str
62
+ Símbolo (p. ej., 'MSTR', 'BTC-USD', 'TSLA').
63
+ start : datetime, opcional
64
+ Fecha inicio (por defecto: ahora - 10 años).
65
+ end : datetime, opcional
66
+ Fecha fin (por defecto: ahora).
67
+ silent : bool
68
+ Si True, no imprime mensajes informativos.
69
+
70
+ Devuelve
71
+ --------
72
+ pandas.DataFrame
73
+ DataFrame de precios (tal como lo devuelve yfinance, columnas OHLCV).
74
+ Si la descarga falla, devuelve DataFrame vacío.
75
+ """
76
+ end = end or datetime.now()
77
+ start = start or (end - timedelta(days=10 * 365))
78
+
79
+ if ticker in all_historical_data and not all_historical_data[ticker].empty:
80
+ if not silent:
81
+ print(f"[data_sources] Usando caché para {ticker} ({len(all_historical_data[ticker])} filas).")
82
+ return all_historical_data[ticker]
83
+
84
+ if not silent:
85
+ print(f"[data_sources] Descargando {ticker} con yfinance... ({start.date()} → {end.date()})")
86
+
87
+ df = yf.download(ticker, start=start, end=end)
88
+
89
+ if not df.empty:
90
+ all_historical_data[ticker] = df
91
+ if not silent:
92
+ print(f"[data_sources] {ticker}: {len(df)} filas descargadas y cacheadas.")
93
+ else:
94
+ if not silent:
95
+ print(f"[data_sources] Error al descargar {ticker} con yfinance.")
96
+
97
+ return all_historical_data.get(ticker, pd.DataFrame())
98
+
99
+
100
+ # ============================================================
101
+ # Descarga BTC 1h desde CryptoCompare y normaliza a cierre 16:00
102
+ # (misma lógica que en tu `procesos 6.py`, empaquetada en función)
103
+ # ============================================================
104
+ def load_btc_hourly_cryptocompare_to_cache(
105
+ symbol: str = "BTC",
106
+ currency: str = "USD",
107
+ limit_per_call: int = 2000,
108
+ years_back: int = 10,
109
+ save_csv_path: str = "btc_hourly_cryptocompare_10_years.csv",
110
+ sleep_seconds: float = 1.0,
111
+ silent: bool = False,
112
+ ) -> pd.DataFrame:
113
+ """
114
+ Descarga datos horarios de BTC desde CryptoCompare, retrocediendo ~N años,
115
+ concatena y normaliza:
116
+ - Convierte índice a 'America/New_York' (o TIMEZONE_TARGET),
117
+ - Filtra la hora 16:00 (cierre),
118
+ - Ajusta nombres de columnas,
119
+ - Guarda CSV,
120
+ - Deja en caché bajo la clave 'BTC-USD'.
121
+
122
+ Parámetros
123
+ ----------
124
+ symbol : str
125
+ Cripto de origen (por defecto: 'BTC').
126
+ currency : str
127
+ Moneda de destino (por defecto: 'USD').
128
+ limit_per_call : int
129
+ Máximo de filas por llamada (CryptoCompare permite 2000).
130
+ years_back : int
131
+ Años hacia atrás (aprox.) para descargar.
132
+ save_csv_path : str
133
+ Ruta donde guardar el CSV final.
134
+ sleep_seconds : float
135
+ Pausa entre llamadas para respetar rate limits.
136
+ silent : bool
137
+ Si True, reduce los prints informativos.
138
+
139
+ Devuelve
140
+ --------
141
+ pandas.DataFrame
142
+ DataFrame final (filtrado a 16:00 en TIMEZONE_TARGET) y cacheado como 'BTC-USD'.
143
+ """
144
+ end_time = datetime.now()
145
+ start_time = end_time - timedelta(days=years_back * 365)
146
+
147
+ to_timestamp = int(end_time.timestamp())
148
+ all_data = []
149
+
150
+ if not silent:
151
+ print(f"[data_sources] Fetching {symbol}/{currency} hourly data from "
152
+ f"{start_time.strftime('%Y-%m-%d')} to {end_time.strftime('%Y-%m-%d')}")
153
+
154
+ while True:
155
+ params = {
156
+ "fsym": symbol,
157
+ "tsym": currency,
158
+ "limit": limit_per_call,
159
+ "toTs": to_timestamp,
160
+ "api_key": CRYPTOCOMPARE_API_KEY, # opcional
161
+ }
162
+
163
+ try:
164
+ response = requests.get(CRYPTOCOMPARE_BASE_URL, params=params)
165
+ data = response.json()
166
+
167
+ if data.get("Response") == "Error":
168
+ if not silent:
169
+ print(f"[data_sources] API Error: {data.get('Message')}")
170
+ break
171
+
172
+ ohlcv_data = data.get("Data", {}).get("Data", [])
173
+ if not ohlcv_data:
174
+ break
175
+
176
+ all_data.extend(ohlcv_data)
177
+
178
+ # Paginación hacia atrás: fijar to_timestamp al primer punto - 1s
179
+ to_timestamp = ohlcv_data[0]["time"] - 1
180
+
181
+ oldest_dt = datetime.fromtimestamp(ohlcv_data[0]["time"])
182
+ if not silent:
183
+ print(f"[data_sources] Hasta: {oldest_dt.strftime('%Y-%m-%d %H:%M:%S')} "
184
+ f"(acumuladas: {len(all_data)})")
185
+
186
+ if oldest_dt <= start_time:
187
+ if not silent:
188
+ print(f"[data_sources] Alcanzado inicio deseado ({start_time.strftime('%Y-%m-%d')}).")
189
+ break
190
+
191
+ time.sleep(sleep_seconds)
192
+
193
+ except requests.exceptions.RequestException as e:
194
+ if not silent:
195
+ print(f"[data_sources] Network error: {e}")
196
+ time.sleep(5)
197
+
198
+ except Exception as e:
199
+ if not silent:
200
+ print(f"[data_sources] Unexpected error: {e}")
201
+ break
202
+
203
+ # Construcción del DataFrame y ordenación
204
+ btc_hour = pd.DataFrame(all_data)
205
+ if btc_hour.empty:
206
+ if not silent:
207
+ print("[data_sources] No se recibieron datos de CryptoCompare.")
208
+ return pd.DataFrame()
209
+
210
+ btc_hour["time"] = pd.to_datetime(btc_hour["time"], unit="s")
211
+ btc_hour.set_index("time", inplace=True)
212
+ btc_hour.sort_index(inplace=True)
213
+
214
+ # Eliminar duplicados por seguridad
215
+ btc_hour = btc_hour[~btc_hour.index.duplicated(keep="first")]
216
+
217
+ # Guardado del bruto unificado (opcional)
218
+ try:
219
+ btc_hour.to_csv(save_csv_path)
220
+ if not silent:
221
+ print(f"[data_sources] Datos guardados en {save_csv_path}")
222
+ except Exception as e:
223
+ if not silent:
224
+ print(f"[data_sources] Aviso: no se pudo guardar CSV ({e})")
225
+
226
+ # Ajuste de zona horaria y filtrado a las 16:00
227
+ btc_hour.index = btc_hour.index.tz_localize("UTC")
228
+ btc_hour.index = btc_hour.index.tz_convert(TIMEZONE_TARGET)
229
+ btc_hour_4pm = btc_hour[btc_hour.index.hour == 16].copy()
230
+
231
+ # Índice solo fecha, columnas con capitalización inicial y dtype datetime64[ns]
232
+ btc_hour_4pm.index = btc_hour_4pm.index.date
233
+ btc_hour_4pm.columns = btc_hour_4pm.columns.str.title()
234
+ btc_hour_4pm.index = pd.to_datetime(btc_hour_4pm.index)
235
+
236
+ # Cachear con clave 'BTC-USD' para compatibilidad con analytics.py
237
+ all_historical_data["BTC-USD"] = btc_hour_4pm
238
+
239
+ if not silent:
240
+ print(f"[data_sources] BTC-USD (16:00 {TIMEZONE_TARGET}) en caché: "
241
+ f"{len(btc_hour_4pm)} filas.")
242
+
243
+ return btc_hour_4pm
244
+
245
+
246
+ # ============================================================
247
+ # Guardar una instantánea del caché a CSVs (uno por ticker)
248
+ # ============================================================
249
+ def save_cache_snapshot(directory: str = "cache_snapshot", silent: bool = False) -> None:
250
+ """
251
+ Guarda todos los DataFrames del caché en CSVs individuales dentro de `directory`.
252
+
253
+ Parámetros
254
+ ----------
255
+ directory : str
256
+ Carpeta donde guardar los CSV (se crea si no existe).
257
+ silent : bool
258
+ Si True, no imprime mensajes.
259
+ """
260
+ os.makedirs(directory, exist_ok=True)
261
+ count = 0
262
+ for ticker, df in all_historical_data.items():
263
+ if isinstance(df, pd.DataFrame) and not df.empty:
264
+ path = os.path.join(directory, f"{ticker.replace('/', '-')}.csv")
265
+ try:
266
+ df.to_csv(path)
267
+ count += 1
268
+ except Exception as e:
269
+ if not silent:
270
+ print(f"[data_sources] No se pudo guardar {ticker} → {e}")
271
+
272
+ if not silent:
273
+ print(f"[data_sources] Instantánea del caché guardada: {count} archivo(s) en '{directory}'.")
274
+
275
+
276
+ __all__ = [
277
+ "all_historical_data",
278
+ "get_data",
279
+ "load_btc_hourly_cryptocompare_to_cache",
280
+ "save_cache_snapshot",
281
+ ]