Download data.py from Quant0/space: direct link, hf CLI and curl.
- Browser
- Download file 3.84 kB
-
https://huggingface.co/spaces/Quant0/space/resolve/4dfd7100ea625bde49b61d2df7c24f6ae0bb938e/data.py
- Command line
-
hf download hf://spaces/Quant0/space@4dfd7100ea625bde49b61d2df7c24f6ae0bb938e/data.py
-
curl -L -o data.py https://huggingface.co/spaces/Quant0/space/resolve/4dfd7100ea625bde49b61d2df7c24f6ae0bb938e/data.py
3.84 kB
| # -*- coding: utf-8 -*- | |
| # Módulo para descarga y preparación de datos desde APIs y web | |
| import pandas as pd | |
| import numpy as np | |
| import requests | |
| import time | |
| import yfinance as yf | |
| from datetime import datetime, timedelta | |
| from config import CRYPTOCOMPARE_API_KEY, CRYPTOCOMPARE_BASE_URL | |
| from utils import limpiar_texto, expand_money, descargar_tabla_web | |
| # Configuración de la API | |
| API_KEY = "TU_API_KEY_DE_CRYPTOCOMPARE" | |
| BASE_URL = "https://min-api.cryptocompare.com/data/v2/histohour" | |
| SYMBOL = "BTC" | |
| CURRENCY = "USD" | |
| LIMIT_PER_CALL = 2000 | |
| # Descarga de datos históricos de BTC | |
| def fetch_btc_hourly_data(): | |
| end_time = datetime.now() | |
| start_time = end_time - timedelta(days=10 * 365) | |
| to_timestamp = int(end_time.timestamp()) | |
| all_data = [] | |
| while True: | |
| params = { | |
| "fsym": SYMBOL, | |
| "tsym": CURRENCY, | |
| "limit": LIMIT_PER_CALL, | |
| "toTs": to_timestamp, | |
| "api_key": API_KEY | |
| } | |
| try: | |
| response = requests.get(BASE_URL, params=params) | |
| data = response.json() | |
| if data['Response'] == 'Error': | |
| print(f"API Error: {data['Message']}") | |
| break | |
| ohlcv_data = data['Data']['Data'] | |
| if not ohlcv_data: | |
| break | |
| all_data.extend(ohlcv_data) | |
| to_timestamp = ohlcv_data[0]['time'] - 1 | |
| oldest_data_time = datetime.fromtimestamp(ohlcv_data[0]['time']) | |
| print(f"Fetched data up to {oldest_data_time.strftime('%Y-%m-%d %H:%M:%S')}. Total records: {len(all_data)}") | |
| if oldest_data_time <= start_time: | |
| print(f"Reached desired start time ({start_time.strftime('%Y-%m-%d')}). Stopping.") | |
| break | |
| time.sleep(1) | |
| except requests.exceptions.RequestException as e: | |
| print(f"Network error: {e}") | |
| time.sleep(5) | |
| except Exception as e: | |
| print(f"An unexpected error occurred: {e}") | |
| break | |
| btc_hour_10y = pd.DataFrame(all_data) | |
| btc_hour_10y['time'] = pd.to_datetime(btc_hour_10y['time'], unit='s') | |
| btc_hour_10y.set_index('time', inplace=True) | |
| btc_hour_10y.sort_index(inplace=True) | |
| btc_hour_10y = btc_hour_10y[~btc_hour_10y.index.duplicated(keep='first')] | |
| btc_hour_10y.to_csv('btc_hourly_cryptocompare_10_years.csv') | |
| print("Data saved to btc_hourly_cryptocompare_10_years.csv") | |
| btc_hour_10y.index = btc_hour_10y.index.tz_localize('UTC').tz_convert('America/New_York') | |
| btc_hour_10y = btc_hour_10y[btc_hour_10y.index.hour == 16] | |
| btc_hour_10y.index = btc_hour_10y.index.date | |
| btc_hour_10y.columns = btc_hour_10y.columns.str.title() | |
| btc_hour_10y.index = pd.to_datetime(btc_hour_10y.index) | |
| return {'BTC-USD': btc_hour_10y} | |
| # Función para obtener opciones financieras | |
| def data_option(ticker, date, option_type, size_of_the_window=4): | |
| price = yf.Ticker(ticker).info['regularMarketPrice'] | |
| chain = yf.Ticker(ticker).option_chain(date) | |
| data = chain.puts.iloc[:, [0, 2, 3, 8, 10, 11, 13]] if option_type == 'put' else chain.calls.iloc[:, [0, 2, 3, 8, 10, 11, 13]] | |
| data['impliedVolatility'] = data['impliedVolatility'].apply(lambda x: f"{x*100:.2f}%") | |
| data = data.sort_values(by='strike', key=lambda x: abs(x - price)) | |
| price_row = pd.DataFrame([[ | |
| '░░░░░░░ Spot Price ░░░░░░░', price, '░'*13, '░'*10, '░'*18, '░'*11, '░'*10 | |
| ]], columns=data.columns) | |
| date_row = pd.DataFrame([[ | |
| f"▓▓▓▓▓▓▓ {date} ▓▓▓▓▓▓▓", '▓'*7, '▓'*13, '▓'*10, '▓'*18, '▓'*11, '▓'*10 | |
| ]], columns=data.columns) | |
| data = pd.concat([data.head(size_of_the_window), price_row]).sort_values(by='strike') | |
| data = pd.concat([date_row, data]) | |
| return data.reset_index(drop=True) | |