File size: 10,968 Bytes
afe1e62 a8d60a1 afe1e62 a8d60a1 afe1e62 a8d60a1 afe1e62 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 |
# π Kraken Trading Data Collection
[](https://huggingface.co/datasets/GotThatData/kraken-trading-data)
[](https://opensource.org/licenses/MIT)
[](https://huggingface.co/datasets/GotThatData/kraken-trading-data)
## Overview
**High-frequency cryptocurrency market data from Kraken exchange** - perfect for algorithmic trading, time-series forecasting, and market microstructure analysis.
This dataset includes **real-time price, volume, and order book data** for 9 major cryptocurrency trading pairs, collected via WebSocket streaming and REST API polling.
---
## π Included Trading Pairs
| Pair | Asset | Base Currency | Typical Daily Volume |
|------|-------|---------------|---------------------|
| `XXBTZUSD` | Bitcoin | USD | $500M - $2B |
| `XETHZUSD` | Ethereum | USD | $200M - $800M |
| `XXRPZUSD` | Ripple (XRP) | USD | $50M - $200M |
| `ADAUSD` | Cardano | USD | $30M - $150M |
| `DOGEUSD` | Dogecoin | USD | $40M - $300M |
| `BNBUSD` | Binance Coin | USD | $20M - $100M |
| `SOLUSD` | Solana | USD | $100M - $400M |
| `DOTUSD` | Polkadot | USD | $15M - $80M |
| `MATICUSD` | Polygon | USD | $20M - $100M |
| `LTCUSD` | Litecoin | USD | $30M - $150M |
---
## π― Use Cases
### 1. **Algorithmic Trading**
- **Backtesting strategies** - Test mean reversion, momentum, arbitrage
- **Order book analysis** - Study bid-ask spreads, depth, liquidity
- **Market making** - Identify optimal quote placement
- **High-frequency trading** - Sub-second price movements
### 2. **Time-Series Forecasting**
- **Price prediction** - LSTM, Transformer, ARIMA models
- **Volatility modeling** - GARCH, stochastic volatility
- **Regime detection** - Bull/bear market classification
- **Anomaly detection** - Flash crashes, wash trading, manipulation
### 3. **Market Microstructure Research**
- **Bid-ask spread dynamics** - How does liquidity evolve?
- **Order flow imbalance** - Predict short-term price movements
- **Trade execution analysis** - Optimal execution strategies (TWAP, VWAP)
- **Cross-exchange arbitrage** - Price discrepancies with Binance, Coinbase
### 4. **Risk Management**
- **Value at Risk (VaR)** - Estimate portfolio risk
- **Correlation analysis** - How do crypto assets move together?
- **Drawdown modeling** - Maximum loss scenarios
- **Liquidity risk** - Can you exit positions without slippage?
---
## π Dataset Structure
```
kraken-trading-data/
βββ trades/ # Individual trade executions
β βββ XXBTZUSD_trades_2024-01.csv
β βββ XETHZUSD_trades_2024-01.csv
β βββ ...
βββ ohlcv/ # OHLCV candlestick data (1min, 5min, 1h, 1d)
β βββ XXBTZUSD_1min.csv
β βββ XXBTZUSD_5min.csv
β βββ ...
βββ orderbook/ # Limit order book snapshots
β βββ XXBTZUSD_orderbook_2024-01.csv
β βββ ...
βββ metadata.json # Collection timestamps, pair info
βββ README.md
```
### Data Fields
#### Trades (`trades/`)
| Field | Type | Description |
|-------|------|-------------|
| `timestamp` | int64 | Unix timestamp (milliseconds) |
| `price` | float64 | Execution price (USD) |
| `volume` | float64 | Trade volume (asset units) |
| `side` | str | `buy` or `sell` (taker side) |
| `trade_id` | str | Unique trade identifier |
#### OHLCV (`ohlcv/`)
| Field | Type | Description |
|-------|------|-------------|
| `timestamp` | int64 | Candle open time (Unix ms) |
| `open` | float64 | Opening price |
| `high` | float64 | Highest price in period |
| `low` | float64 | Lowest price in period |
| `close` | float64 | Closing price |
| `volume` | float64 | Total volume traded |
| `trade_count` | int32 | Number of trades |
#### Order Book (`orderbook/`)
| Field | Type | Description |
|-------|------|-------------|
| `timestamp` | int64 | Snapshot time (Unix ms) |
| `side` | str | `bid` or `ask` |
| `price` | float64 | Limit order price |
| `volume` | float64 | Volume available at price level |
| `cumulative_volume` | float64 | Cumulative depth |
---
## π Quick Start
### Load the Dataset
```python
from datasets import load_dataset
dataset = load_dataset("GotThatData/kraken-trading-data")
```
### Example: Load Bitcoin Trades
```python
import pandas as pd
# Load Bitcoin trades for January 2024
df = pd.read_csv("hf://datasets/GotThatData/kraken-trading-data/trades/XXBTZUSD_trades_2024-01.csv")
# Convert timestamp to datetime
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
# Set as index
df = df.set_index('timestamp')
# Display first rows
print(df.head())
```
**Output:**
```
price volume side trade_id
timestamp
2024-01-01 00:00:01.234 42150.5 0.025000 buy 1704067201234-1
2024-01-01 00:00:01.567 42149.8 0.100000 sell 1704067201567-2
...
```
### Example: Resample to 1-Hour OHLCV
```python
# Resample trades to hourly candles
ohlcv = df.resample('1H').agg({
'price': ['first', 'max', 'min', 'last'],
'volume': 'sum',
'trade_id': 'count'
})
# Flatten column names
ohlcv.columns = ['open', 'high', 'low', 'close', 'volume', 'trade_count']
print(ohlcv.head())
```
### Example: Calculate Moving Average Crossover
```python
import matplotlib.pyplot as plt
# Load 1-minute OHLCV
df = pd.read_csv("hf://datasets/GotThatData/kraken-trading-data/ohlcv/XXBTZUSD_1min.csv")
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
df = df.set_index('timestamp')
# Calculate moving averages
df['MA_20'] = df['close'].rolling(window=20).mean()
df['MA_50'] = df['close'].rolling(window=50).mean()
# Plot
plt.figure(figsize=(14, 7))
plt.plot(df['close'], label='BTC Price', alpha=0.5)
plt.plot(df['MA_20'], label='20-period MA')
plt.plot(df['MA_50'], label='50-period MA')
plt.legend()
plt.title('Bitcoin Price with Moving Averages')
plt.show()
```
### Example: Order Book Visualization
```python
import seaborn as sns
# Load order book snapshot
ob = pd.read_csv("hf://datasets/GotThatData/kraken-trading-data/orderbook/XXBTZUSD_orderbook_2024-01.csv")
# Filter for a specific timestamp
snapshot = ob[ob['timestamp'] == ob['timestamp'].iloc[0]]
# Separate bids and asks
bids = snapshot[snapshot['side'] == 'bid'].sort_values('price', ascending=False)
asks = snapshot[snapshot['side'] == 'ask'].sort_values('price')
# Plot depth chart
plt.figure(figsize=(12, 6))
plt.step(bids['price'], bids['cumulative_volume'], where='pre', label='Bids', color='green')
plt.step(asks['price'], asks['cumulative_volume'], where='post', label='Asks', color='red')
plt.xlabel('Price (USD)')
plt.ylabel('Cumulative Volume (BTC)')
plt.title('BTC/USD Order Book Depth')
plt.legend()
plt.show()
```
---
## π Sample Analysis: Predict Next-Hour Price Movement
```python
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
# Load hourly OHLCV
df = pd.read_csv("hf://datasets/GotThatData/kraken-trading-data/ohlcv/XXBTZUSD_1h.csv")
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
df = df.set_index('timestamp')
# Feature engineering
df['returns'] = df['close'].pct_change()
df['volatility'] = df['returns'].rolling(window=24).std()
df['volume_ma'] = df['volume'].rolling(window=24).mean()
# Target: 1 if price goes up next hour, 0 otherwise
df['target'] = (df['close'].shift(-1) > df['close']).astype(int)
# Drop NaNs
df = df.dropna()
# Features and target
features = ['open', 'high', 'low', 'close', 'volume', 'returns', 'volatility', 'volume_ma']
X = df[features]
y = df['target']
# Split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=False)
# Train model
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
# Evaluate
accuracy = model.score(X_test, y_test)
print(f"Accuracy: {accuracy:.2%}")
```
---
## π¬ Research Applications
### Published Papers Using This Dataset
*(Open a PR to add your work!)*
### Potential Research Questions
1. **Can transformers outperform LSTMs for crypto price prediction?**
2. **How does order book imbalance predict short-term price movements?**
3. **What's the optimal rebalancing frequency for a crypto portfolio?**
4. **Do Twitter sentiment signals correlate with price volatility?**
5. **Can you detect wash trading or market manipulation in the data?**
---
## π Citation
If you use this dataset in your research, please cite:
```bibtex
@dataset{daugherty2024kraken,
author = {Bryan Daugherty},
title = {Kraken Trading Data Collection},
year = {2024},
publisher = {Hugging Face},
url = {https://huggingface.co/datasets/GotThatData/kraken-trading-data}
}
```
---
## π Related Resources
- **Kraken API Docs:** [https://docs.kraken.com/rest/](https://docs.kraken.com/rest/)
- **ccxt Library:** [https://github.com/ccxt/ccxt](https://github.com/ccxt/ccxt) - Unified crypto exchange API
- **TA-Lib:** [https://ta-lib.org/](https://ta-lib.org/) - Technical analysis library
---
## βοΈ Data Collection Methodology
Data was collected using:
1. **Kraken WebSocket API** - Real-time trade stream (sub-second latency)
2. **Kraken REST API** - Order book snapshots (every 10 seconds)
3. **ccxt Library** - Normalized OHLCV data (1min, 5min, 1h, 1d intervals)
**Collection Period:** January 2024 - December 2024 (ongoing updates)
**Update Frequency:** Daily (new data added at 00:00 UTC)
---
## π License
MIT License - free for academic and commercial use.
**Disclaimer:** This data is for research and educational purposes only. Past performance does not guarantee future results. Cryptocurrency trading involves significant risk.
---
## π Acknowledgments
- **Kraken Exchange** - For providing free, high-quality market data APIs
- **ccxt Community** - For building robust exchange integration tools
- **Hugging Face** - For hosting and serving this dataset
---
## π Known Issues & Future Work
- **Missing Data:** Some gaps during exchange maintenance windows (< 0.1% of total data)
- **Timezone:** All timestamps are UTC
- **Delisting:** BNBUSD was delisted in June 2024 (data ends June 30)
**Roadmap:**
- [ ] Add L2 order book data (full depth, not just top 20 levels)
- [ ] Include funding rate data for perpetual futures
- [ ] Add cross-exchange arbitrage opportunities dataset
- [ ] Create Gradio Space for interactive data exploration
---
## π¬ Feedback & Contributions
Found a bug? Want to request additional pairs or features?
- **Discussions:** [Open a discussion](https://huggingface.co/datasets/GotThatData/kraken-trading-data/discussions)
- **Contact:** YourFriends@smartledger.solutions
---
*"In trading, the only constant is change. Adapt or fade away."* β Paul Tudor Jones
|