Download qrypto/data.py from Qempireautomation/qrypto-engine: direct link, hf CLI and curl.
- Browser
- Download file 5.98 kB
-
https://huggingface.co/Qempireautomation/qrypto-engine/resolve/main/qrypto/data.py
- Command line
-
hf download hf://Qempireautomation/qrypto-engine/qrypto/data.py
-
curl -L -o data.py https://huggingface.co/Qempireautomation/qrypto-engine/resolve/main/qrypto/data.py
5.98 kB
| """Market data: OHLCV candles from public exchange endpoints or local files. | |
| Public candle endpoints need no API key. All adapters return a pandas | |
| DataFrame with columns [timestamp(UTC), open, high, low, close, volume], | |
| sorted ascending, one row per candle. | |
| """ | |
| from __future__ import annotations | |
| import time | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import Optional | |
| import pandas as pd | |
| import requests | |
| COLUMNS = ["timestamp", "open", "high", "low", "close", "volume"] | |
| _TF_SECONDS = { | |
| "1m": 60, "5m": 300, "15m": 900, "30m": 1800, | |
| "1h": 3600, "2h": 7200, "4h": 14400, "1d": 86400, | |
| } | |
| def timeframe_seconds(tf: str) -> int: | |
| if tf not in _TF_SECONDS: | |
| raise ValueError(f"unsupported timeframe {tf}; use one of {list(_TF_SECONDS)}") | |
| return _TF_SECONDS[tf] | |
| def _frame(rows, unit="ms") -> pd.DataFrame: | |
| df = pd.DataFrame(rows, columns=COLUMNS) | |
| df["timestamp"] = pd.to_datetime(df["timestamp"], unit=unit, utc=True) | |
| for c in ["open", "high", "low", "close", "volume"]: | |
| df[c] = pd.to_numeric(df[c], errors="coerce") | |
| df = df.dropna().sort_values("timestamp").drop_duplicates("timestamp") | |
| return df.reset_index(drop=True) | |
| class ExchangeInfo: | |
| name: str | |
| symbol_format: str # e.g. "BTCUSDT" or "XBTUSD" | |
| class MarketData: | |
| """Fetches candles from a public exchange REST endpoint.""" | |
| def __init__(self, exchange: str = "binance", session: Optional[requests.Session] = None, timeout: int = 20): | |
| self.exchange = exchange.lower() | |
| self.session = session or requests.Session() | |
| self.timeout = timeout | |
| if self.exchange not in ("binance", "kraken", "coinbase"): | |
| raise ValueError("exchange must be binance, kraken or coinbase") | |
| # --- symbol helpers ------------------------------------------------- | |
| def split(symbol: str) -> tuple[str, str]: | |
| base, quote = symbol.upper().split("/") | |
| return base, quote | |
| def native_symbol(self, symbol: str) -> str: | |
| base, quote = self.split(symbol) | |
| if self.exchange == "binance": | |
| return f"{base}{quote}" | |
| if self.exchange == "kraken": | |
| base = "XBT" if base == "BTC" else base | |
| return f"{base}{quote}" | |
| return f"{base}-{quote}" # coinbase | |
| # --- fetch ------------------------------------------------------------ | |
| def candles(self, symbol: str, timeframe: str = "1h", limit: int = 500) -> pd.DataFrame: | |
| tf_s = timeframe_seconds(timeframe) | |
| if self.exchange == "binance": | |
| r = self.session.get( | |
| "https://api.binance.com/api/v3/klines", | |
| params={"symbol": self.native_symbol(symbol), "interval": timeframe, "limit": min(limit, 1000)}, | |
| timeout=self.timeout, | |
| ) | |
| r.raise_for_status() | |
| rows = [[k[0], k[1], k[2], k[3], k[4], k[5]] for k in r.json()] | |
| return _frame(rows, "ms") | |
| if self.exchange == "kraken": | |
| r = self.session.get( | |
| "https://api.kraken.com/0/public/OHLC", | |
| params={"pair": self.native_symbol(symbol), "interval": tf_s // 60}, | |
| timeout=self.timeout, | |
| ) | |
| r.raise_for_status() | |
| payload = r.json() | |
| if payload.get("error"): | |
| raise RuntimeError(f"kraken: {payload['error']}") | |
| key = next(k for k in payload["result"] if k != "last") | |
| rows = [[k[0], k[1], k[2], k[3], k[4], k[6]] for k in payload["result"][key]] | |
| return _frame(rows, "s").tail(limit).reset_index(drop=True) | |
| # coinbase exchange public candles: [time, low, high, open, close, volume] | |
| end = int(time.time()) | |
| start = end - tf_s * min(limit, 300) | |
| r = self.session.get( | |
| f"https://api.exchange.coinbase.com/products/{self.native_symbol(symbol)}/candles", | |
| params={"granularity": tf_s, "start": start, "end": end}, | |
| timeout=self.timeout, | |
| ) | |
| r.raise_for_status() | |
| rows = [[k[0], k[3], k[2], k[1], k[4], k[5]] for k in r.json()] | |
| return _frame(rows, "s") | |
| def last_price(self, symbol: str) -> float: | |
| df = self.candles(symbol, "1m", limit=2) | |
| return float(df["close"].iloc[-1]) | |
| def load_csv(path: str | Path, symbol: Optional[str] = None) -> pd.DataFrame: | |
| """Load candles from CSV with columns timestamp[,asset],open,high,low,close,volume.""" | |
| df = pd.read_csv(path) | |
| if "asset" in df.columns and symbol: | |
| df = df[df["asset"] == symbol] | |
| if "datetime" in df.columns and "timestamp" not in df.columns: | |
| df = df.rename(columns={"datetime": "timestamp"}) | |
| df = df[COLUMNS].copy() | |
| df["timestamp"] = pd.to_datetime(df["timestamp"], utc=True) | |
| return df.sort_values("timestamp").reset_index(drop=True) | |
| def load_parquet(path: str | Path) -> pd.DataFrame: | |
| df = pd.read_parquet(path) | |
| if "datetime" in df.columns: | |
| df = df.rename(columns={"datetime": "timestamp"}) | |
| df = df[COLUMNS].copy() | |
| df["timestamp"] = pd.to_datetime(df["timestamp"], utc=True) | |
| return df.sort_values("timestamp").reset_index(drop=True) | |
| def synthetic(n: int = 2000, seed: int = 7, start_price: float = 30000.0, tf: str = "1h") -> pd.DataFrame: | |
| """Random-walk candles for tests. Not a market model — just plumbing data.""" | |
| import numpy as np | |
| rng = np.random.default_rng(seed) | |
| rets = rng.normal(0, 0.01, n) | |
| close = start_price * np.exp(np.cumsum(rets)) | |
| open_ = np.concatenate([[start_price], close[:-1]]) | |
| high = np.maximum(open_, close) * (1 + rng.uniform(0, 0.005, n)) | |
| low = np.minimum(open_, close) * (1 - rng.uniform(0, 0.005, n)) | |
| vol = rng.uniform(10, 100, n) | |
| ts = pd.date_range("2024-01-01", periods=n, freq=f"{timeframe_seconds(tf)}s", tz="UTC") | |
| return pd.DataFrame({"timestamp": ts, "open": open_, "high": high, "low": low, "close": close, "volume": vol}) | |