Enhanced README with examples, use cases, and citations
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118---license: mittask_categories:- time-series-forecastinglanguage:- entags:- finance- cryptocurrency- trading- krakenpretty_name: kraken-trading-datasize_categories:- 10K<n<100K---Kraken Trading Data CollectionOverviewThis repository contains tools for collecting cryptocurrency trading data from the Kraken exchange. The dataset includes real-time price, volume, and order book data for major cryptocurrency pairs.Data DescriptionIncluded Trading PairsXXBTZUSD (Bitcoin/USD)XETHZUSD (Ethereum/USD)XXRPZUSD (Ripple/USD)ADAUSD (Cardano/USD)DOGEUSD (Dogecoin/USD)BNBUSD (Binance Coin/USD)SOLUSD (Solana/USD)DOTUSD (Polkadot/USD)MATICUSD (Polygon/USD)LTCUSD (Litecoin/USD)Data FieldsFieldTypeDescriptiontimestampdatetimeUTC timestamp of data collectionpairstringTrading pair identifierpricefloatLast traded pricevolumefloat24h trading volumebidfloatBest bid priceaskfloatBest ask pricelowfloat24h low pricehighfloat24h high pricevwapfloatVolume weighted average pricetradesintegerNumber of tradesData SplitsTraining: 1000 data points per pairValidation: 200 data points per pairTest: 200 data points per pairSetup InstructionsPrerequisitesPython 3.8 or higherKraken API credentialsInstallationClone the repository:bashCopygit clone https://huggingface.co/datasets/GotThatData/kraken-trading-datacd kraken-trading-dataInstall required packages:bashCopypip install -r requirements.txtCreate API credentials file:Create a file named kraken.key with your Kraken API credentials:textCopykey=your-api-keysecret=your-api-secretUsageRun the data collection script:bashCopypython kraken_data_collector.pyThe script will create three CSV files in the data directory:data/training/kraken_trades.csvdata/validation/kraken_trades.csvdata/test/kraken_trades.csvFile StructureCopykraken-trading-data/βββ README.mdβββ requirements.txtβββ kraken_data_collector.pyβββ kraken.key (not included in repository)βββ data/βββ training/β βββ kraken_trades.csvβββ validation/β βββ kraken_trades.csvβββ test/βββ kraken_trades.csvData Collection ProcessData is collected using Kraken's public APICollection frequency: One data point every 2 seconds per pairAutomatic handling of API rate limitsComprehensive error loggingData validation and cleaningImportant NotesThe kraken.key file containing API credentials should never be shared or committed to the repositoryBe mindful of Kraken's API rate limitsAll timestamps are in UTCLoggingThe script creates a log file kraken_data_collection.log that includes:Data collection progressError messagesData summary statisticsLicenseMIT LicenseContactFor questions or issues, please open an issue in the repository.CitationIf you use this dataset in your research, please cite:Copy@dataset{kraken_trading_data,author = {GotThatData},title = {Kraken Trading Data Collection},year = {2024},publisher = {Hugging Face},url = {https://huggingface.co/datasets/GotThatData/kraken-trading-data}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348# π 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```pythonfrom datasets import load_datasetdataset = load_dataset("GotThatData/kraken-trading-data")```### Example: Load Bitcoin Trades```pythonimport pandas as pd# Load Bitcoin trades for January 2024df = pd.read_csv("hf://datasets/GotThatData/kraken-trading-data/trades/XXBTZUSD_trades_2024-01.csv")# Convert timestamp to datetimedf['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')# Set as indexdf = df.set_index('timestamp')# Display first rowsprint(df.head())```**Output:**```price volume side trade_idtimestamp2024-01-01 00:00:01.234 42150.5 0.025000 buy 1704067201234-12024-01-01 00:00:01.567 42149.8 0.100000 sell 1704067201567-2...```### Example: Resample to 1-Hour OHLCV```python# Resample trades to hourly candlesohlcv = df.resample('1H').agg({'price': ['first', 'max', 'min', 'last'],'volume': 'sum','trade_id': 'count'})# Flatten column namesohlcv.columns = ['open', 'high', 'low', 'close', 'volume', 'trade_count']print(ohlcv.head())```### Example: Calculate Moving Average Crossover```pythonimport matplotlib.pyplot as plt# Load 1-minute OHLCVdf = 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 averagesdf['MA_20'] = df['close'].rolling(window=20).mean()df['MA_50'] = df['close'].rolling(window=50).mean()# Plotplt.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```pythonimport seaborn as sns# Load order book snapshotob = pd.read_csv("hf://datasets/GotThatData/kraken-trading-data/orderbook/XXBTZUSD_orderbook_2024-01.csv")# Filter for a specific timestampsnapshot = ob[ob['timestamp'] == ob['timestamp'].iloc[0]]# Separate bids and asksbids = snapshot[snapshot['side'] == 'bid'].sort_values('price', ascending=False)asks = snapshot[snapshot['side'] == 'ask'].sort_values('price')# Plot depth chartplt.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```pythonfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import train_test_split# Load hourly OHLCVdf = 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 engineeringdf['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 otherwisedf['target'] = (df['close'].shift(-1) > df['close']).astype(int)# Drop NaNsdf = df.dropna()# Features and targetfeatures = ['open', 'high', 'low', 'close', 'volume', 'returns', 'volatility', 'volume_ma']X = df[features]y = df['target']# SplitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=False)# Train modelmodel = RandomForestClassifier(n_estimators=100, random_state=42)model.fit(X_train, y_train)# Evaluateaccuracy = 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 Questions1. **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?**---## π CitationIf 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 MethodologyData 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)---## π LicenseMIT 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 & ContributionsFound 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
README.md+345-115