Qempireautomation commited on
Commit
15151cd
·
verified ·
1 Parent(s): 6c6528a

Add market data adapters

Browse files
Files changed (1) hide show
  1. qrypto/data.py +146 -0
qrypto/data.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Market data: OHLCV candles from public exchange endpoints or local files.
2
+
3
+ Public candle endpoints need no API key. All adapters return a pandas
4
+ DataFrame with columns [timestamp(UTC), open, high, low, close, volume],
5
+ sorted ascending, one row per candle.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import time
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Optional
13
+
14
+ import pandas as pd
15
+ import requests
16
+
17
+ COLUMNS = ["timestamp", "open", "high", "low", "close", "volume"]
18
+
19
+ _TF_SECONDS = {
20
+ "1m": 60, "5m": 300, "15m": 900, "30m": 1800,
21
+ "1h": 3600, "2h": 7200, "4h": 14400, "1d": 86400,
22
+ }
23
+
24
+
25
+ def timeframe_seconds(tf: str) -> int:
26
+ if tf not in _TF_SECONDS:
27
+ raise ValueError(f"unsupported timeframe {tf}; use one of {list(_TF_SECONDS)}")
28
+ return _TF_SECONDS[tf]
29
+
30
+
31
+ def _frame(rows, unit="ms") -> pd.DataFrame:
32
+ df = pd.DataFrame(rows, columns=COLUMNS)
33
+ df["timestamp"] = pd.to_datetime(df["timestamp"], unit=unit, utc=True)
34
+ for c in ["open", "high", "low", "close", "volume"]:
35
+ df[c] = pd.to_numeric(df[c], errors="coerce")
36
+ df = df.dropna().sort_values("timestamp").drop_duplicates("timestamp")
37
+ return df.reset_index(drop=True)
38
+
39
+
40
+ @dataclass
41
+ class ExchangeInfo:
42
+ name: str
43
+ symbol_format: str # e.g. "BTCUSDT" or "XBTUSD"
44
+
45
+
46
+ class MarketData:
47
+ """Fetches candles from a public exchange REST endpoint."""
48
+
49
+ def __init__(self, exchange: str = "binance", session: Optional[requests.Session] = None, timeout: int = 20):
50
+ self.exchange = exchange.lower()
51
+ self.session = session or requests.Session()
52
+ self.timeout = timeout
53
+ if self.exchange not in ("binance", "kraken", "coinbase"):
54
+ raise ValueError("exchange must be binance, kraken or coinbase")
55
+
56
+ # --- symbol helpers -------------------------------------------------
57
+ @staticmethod
58
+ def split(symbol: str) -> tuple[str, str]:
59
+ base, quote = symbol.upper().split("/")
60
+ return base, quote
61
+
62
+ def native_symbol(self, symbol: str) -> str:
63
+ base, quote = self.split(symbol)
64
+ if self.exchange == "binance":
65
+ return f"{base}{quote}"
66
+ if self.exchange == "kraken":
67
+ base = "XBT" if base == "BTC" else base
68
+ return f"{base}{quote}"
69
+ return f"{base}-{quote}" # coinbase
70
+
71
+ # --- fetch ------------------------------------------------------------
72
+ def candles(self, symbol: str, timeframe: str = "1h", limit: int = 500) -> pd.DataFrame:
73
+ tf_s = timeframe_seconds(timeframe)
74
+ if self.exchange == "binance":
75
+ r = self.session.get(
76
+ "https://api.binance.com/api/v3/klines",
77
+ params={"symbol": self.native_symbol(symbol), "interval": timeframe, "limit": min(limit, 1000)},
78
+ timeout=self.timeout,
79
+ )
80
+ r.raise_for_status()
81
+ rows = [[k[0], k[1], k[2], k[3], k[4], k[5]] for k in r.json()]
82
+ return _frame(rows, "ms")
83
+ if self.exchange == "kraken":
84
+ r = self.session.get(
85
+ "https://api.kraken.com/0/public/OHLC",
86
+ params={"pair": self.native_symbol(symbol), "interval": tf_s // 60},
87
+ timeout=self.timeout,
88
+ )
89
+ r.raise_for_status()
90
+ payload = r.json()
91
+ if payload.get("error"):
92
+ raise RuntimeError(f"kraken: {payload['error']}")
93
+ key = next(k for k in payload["result"] if k != "last")
94
+ rows = [[k[0], k[1], k[2], k[3], k[4], k[6]] for k in payload["result"][key]]
95
+ return _frame(rows, "s").tail(limit).reset_index(drop=True)
96
+ # coinbase exchange public candles: [time, low, high, open, close, volume]
97
+ end = int(time.time())
98
+ start = end - tf_s * min(limit, 300)
99
+ r = self.session.get(
100
+ f"https://api.exchange.coinbase.com/products/{self.native_symbol(symbol)}/candles",
101
+ params={"granularity": tf_s, "start": start, "end": end},
102
+ timeout=self.timeout,
103
+ )
104
+ r.raise_for_status()
105
+ rows = [[k[0], k[3], k[2], k[1], k[4], k[5]] for k in r.json()]
106
+ return _frame(rows, "s")
107
+
108
+ def last_price(self, symbol: str) -> float:
109
+ df = self.candles(symbol, "1m", limit=2)
110
+ return float(df["close"].iloc[-1])
111
+
112
+
113
+ def load_csv(path: str | Path, symbol: Optional[str] = None) -> pd.DataFrame:
114
+ """Load candles from CSV with columns timestamp[,asset],open,high,low,close,volume."""
115
+ df = pd.read_csv(path)
116
+ if "asset" in df.columns and symbol:
117
+ df = df[df["asset"] == symbol]
118
+ if "datetime" in df.columns and "timestamp" not in df.columns:
119
+ df = df.rename(columns={"datetime": "timestamp"})
120
+ df = df[COLUMNS].copy()
121
+ df["timestamp"] = pd.to_datetime(df["timestamp"], utc=True)
122
+ return df.sort_values("timestamp").reset_index(drop=True)
123
+
124
+
125
+ def load_parquet(path: str | Path) -> pd.DataFrame:
126
+ df = pd.read_parquet(path)
127
+ if "datetime" in df.columns:
128
+ df = df.rename(columns={"datetime": "timestamp"})
129
+ df = df[COLUMNS].copy()
130
+ df["timestamp"] = pd.to_datetime(df["timestamp"], utc=True)
131
+ return df.sort_values("timestamp").reset_index(drop=True)
132
+
133
+
134
+ def synthetic(n: int = 2000, seed: int = 7, start_price: float = 30000.0, tf: str = "1h") -> pd.DataFrame:
135
+ """Random-walk candles for tests. Not a market model — just plumbing data."""
136
+ import numpy as np
137
+
138
+ rng = np.random.default_rng(seed)
139
+ rets = rng.normal(0, 0.01, n)
140
+ close = start_price * np.exp(np.cumsum(rets))
141
+ open_ = np.concatenate([[start_price], close[:-1]])
142
+ high = np.maximum(open_, close) * (1 + rng.uniform(0, 0.005, n))
143
+ low = np.minimum(open_, close) * (1 - rng.uniform(0, 0.005, n))
144
+ vol = rng.uniform(10, 100, n)
145
+ ts = pd.date_range("2024-01-01", periods=n, freq=f"{timeframe_seconds(tf)}s", tz="UTC")
146
+ return pd.DataFrame({"timestamp": ts, "open": open_, "high": high, "low": low, "close": close, "volume": vol})