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 3 |
+
from datetime import datetime
|
| 4 |
+
import time
|
| 5 |
+
import os
|
| 6 |
+
from typing import Dict, List, Optional
|
| 7 |
+
import logging
|
| 8 |
+
|
| 9 |
+
# Set up logging
|
| 10 |
+
logging.basicConfig(
|
| 11 |
+
level=logging.INFO,
|
| 12 |
+
format='%(asctime)s - %(levelname)s - %(message)s',
|
| 13 |
+
handlers=[
|
| 14 |
+
logging.FileHandler('kraken_data_collection.log'),
|
| 15 |
+
logging.StreamHandler()
|
| 16 |
+
]
|
| 17 |
+
)
|
| 18 |
+
logger = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
+
class KrakenDataCollector:
|
| 21 |
+
"""Handles data collection from Kraken API"""
|
| 22 |
+
|
| 23 |
+
def __init__(self, api_key_path: str):
|
| 24 |
+
self.api = krakenex.API()
|
| 25 |
+
try:
|
| 26 |
+
self.api.load_key(api_key_path)
|
| 27 |
+
logger.info("Successfully loaded Kraken API key")
|
| 28 |
+
except Exception as e:
|
| 29 |
+
logger.error(f"Failed to load API key: {e}")
|
| 30 |
+
raise
|
| 31 |
+
|
| 32 |
+
# Trading pairs to collect data for
|
| 33 |
+
self.pairs = [
|
| 34 |
+
"XXBTZUSD", # Bitcoin
|
| 35 |
+
"XETHZUSD", # Ethereum
|
| 36 |
+
"XXRPZUSD", # Ripple
|
| 37 |
+
"ADAUSD", # Cardano
|
| 38 |
+
"DOGEUSD", # Dogecoin
|
| 39 |
+
"BNBUSD", # Binance Coin
|
| 40 |
+
"SOLUSD", # Solana
|
| 41 |
+
"DOTUSD", # Polkadot
|
| 42 |
+
"MATICUSD", # Polygon
|
| 43 |
+
"LTCUSD" # Litecoin
|
| 44 |
+
]
|
| 45 |
+
|
| 46 |
+
def fetch_ticker_data(self, pair: str) -> Optional[Dict]:
|
| 47 |
+
"""Fetch ticker data for a single pair"""
|
| 48 |
+
try:
|
| 49 |
+
response = self.api.query_public('Ticker', {'pair': pair})
|
| 50 |
+
|
| 51 |
+
if 'error' in response and response['error']:
|
| 52 |
+
logger.error(f"Kraken API error for {pair}: {response['error']}")
|
| 53 |
+
return None
|
| 54 |
+
|
| 55 |
+
data = response['result']
|
| 56 |
+
pair_data = list(data.values())[0]
|
| 57 |
+
|
| 58 |
+
return {
|
| 59 |
+
'timestamp': datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S'),
|
| 60 |
+
'pair': pair,
|
| 61 |
+
'price': float(pair_data['c'][0]), # Last trade closed price
|
| 62 |
+
'volume': float(pair_data['v'][0]), # 24h volume
|
| 63 |
+
'bid': float(pair_data['b'][0]), # Best bid
|
| 64 |
+
'ask': float(pair_data['a'][0]), # Best ask
|
| 65 |
+
'low': float(pair_data['l'][0]), # 24h low
|
| 66 |
+
'high': float(pair_data['h'][0]), # 24h high
|
| 67 |
+
'vwap': float(pair_data['p'][0]), # 24h VWAP
|
| 68 |
+
'trades': int(pair_data['t'][0]) # Number of trades
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
except Exception as e:
|
| 72 |
+
logger.error(f"Error fetching data for {pair}: {e}")
|
| 73 |
+
return None
|
| 74 |
+
|
| 75 |
+
def create_data_directories(self) -> None:
|
| 76 |
+
"""Create directory structure for data storage"""
|
| 77 |
+
for split in ['training', 'validation', 'test']:
|
| 78 |
+
directory = f'data/{split}'
|
| 79 |
+
if not os.path.exists(directory):
|
| 80 |
+
os.makedirs(directory)
|
| 81 |
+
logger.info(f"Created directory: {directory}")
|
| 82 |
+
|
| 83 |
+
def save_data_to_csv(self, split: str, num_rows: int, delay: int = 2) -> None:
|
| 84 |
+
"""
|
| 85 |
+
Collect and save data for all pairs
|
| 86 |
+
|
| 87 |
+
Args:
|
| 88 |
+
split: Data split type ('training', 'validation', 'test')
|
| 89 |
+
num_rows: Number of data points to collect per pair
|
| 90 |
+
delay: Delay between API calls in seconds
|
| 91 |
+
"""
|
| 92 |
+
try:
|
| 93 |
+
records = []
|
| 94 |
+
|
| 95 |
+
for i in range(num_rows):
|
| 96 |
+
logger.info(f"Collecting row {i+1}/{num_rows}")
|
| 97 |
+
|
| 98 |
+
for pair in self.pairs:
|
| 99 |
+
record = self.fetch_ticker_data(pair)
|
| 100 |
+
if record:
|
| 101 |
+
records.append(record)
|
| 102 |
+
|
| 103 |
+
if i < num_rows - 1: # Don't sleep after last iteration
|
| 104 |
+
time.sleep(delay) # Respect API rate limits
|
| 105 |
+
|
| 106 |
+
# Create DataFrame and save to CSV
|
| 107 |
+
df = pd.DataFrame(records)
|
| 108 |
+
file_path = f"data/{split}/kraken_trades.csv"
|
| 109 |
+
|
| 110 |
+
# Create directory if it doesn't exist
|
| 111 |
+
os.makedirs(os.path.dirname(file_path), exist_ok=True)
|
| 112 |
+
|
| 113 |
+
# Save data
|
| 114 |
+
df.to_csv(file_path, index=False)
|
| 115 |
+
logger.info(f"Successfully saved {len(records)} records to {file_path}")
|
| 116 |
+
|
| 117 |
+
# Print data summary
|
| 118 |
+
logger.info("\nData Summary:")
|
| 119 |
+
logger.info(f"Total records: {len(records)}")
|
| 120 |
+
logger.info(f"Pairs collected: {len(df['pair'].unique())}")
|
| 121 |
+
logger.info(f"Time range: {df['timestamp'].min()} to {df['timestamp'].max()}")
|
| 122 |
+
|
| 123 |
+
except Exception as e:
|
| 124 |
+
logger.error(f"Error saving data: {e}")
|
| 125 |
+
raise
|
| 126 |
+
|
| 127 |
+
def main():
|
| 128 |
+
"""Main function to run data collection"""
|
| 129 |
+
try:
|
| 130 |
+
# Initialize collector
|
| 131 |
+
collector = KrakenDataCollector("kraken.key")
|
| 132 |
+
|
| 133 |
+
# Create directory structure
|
| 134 |
+
collector.create_data_directories()
|
| 135 |
+
|
| 136 |
+
# Collect data for each split
|
| 137 |
+
splits_config = {
|
| 138 |
+
'training': 1000, # 1000 rows for training
|
| 139 |
+
'validation': 200, # 200 rows for validation
|
| 140 |
+
'test': 200 # 200 rows for test
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
for split, num_rows in splits_config.items():
|
| 144 |
+
logger.info(f"\nCollecting {split} data...")
|
| 145 |
+
collector.save_data_to_csv(split=split, num_rows=num_rows)
|
| 146 |
+
|
| 147 |
+
logger.info("Data collection completed successfully!")
|
| 148 |
+
|
| 149 |
+
except Exception as e:
|
| 150 |
+
logger.error(f"Fatal error in data collection: {e}")
|
| 151 |
+
raise
|
| 152 |
+
|
| 153 |
+
if __name__ == "__main__":
|
| 154 |
+
main()
|