Spaces:
Runtime error
Runtime error
| from binance.client import Client | |
| import pandas as pd | |
| from datetime import datetime | |
| class BinanceClient: | |
| def __init__(self, api_key, api_secret): | |
| """Initialize the Binance client with user's API key and secret.""" | |
| self.client = Client(api_key, api_secret) | |
| def fetch_historical_prices(self, symbol, interval, days): | |
| """Fetch historical prices for a given symbol and interval. | |
| Args: | |
| symbol (str): The cryptocurrency symbol, e.g., 'BTCUSDT'. | |
| interval (str): The candlestick chart intervals. | |
| days (int): Number of days back to fetch data for. | |
| Returns: | |
| pd.DataFrame: A DataFrame with columns: date, open, high, low, close, volume. | |
| """ | |
| # Calculate the timestamp for 'days' days ago | |
| end_time = datetime.utcnow() | |
| start_str = (end_time - pd.Timedelta(days=days)).strftime('%d %b %Y %H:%M:%S') | |
| # Fetch historical candlestick data from Binance | |
| candles = self.client.get_historical_klines(symbol, interval, start_str) | |
| # Create a DataFrame from the fetched data | |
| df = pd.DataFrame(candles, columns=['date', 'open', 'high', 'low', 'close', 'volume', 'close_time', 'quote_asset_volume', 'number_of_trades', 'taker_buy_base_asset_volume', 'taker_buy_quote_asset_volume', 'ignore']) | |
| # Convert timestamp to datetime and adjust columns | |
| df['date'] = pd.to_datetime(df['date'], unit='ms') | |
| df = df[['date', 'open', 'high', 'low', 'close', 'volume']].copy() | |
| # Convert columns to the appropriate data type | |
| df['open'] = df['open'].astype(float) | |
| df['high'] = df['high'].astype(float) | |
| df['low'] = df['low'].astype(float) | |
| df['close'] = df['close'].astype(float) | |
| df['volume'] = df['volume'].astype(float) | |
| return df | |