File size: 3,272 Bytes
8481f3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import pandas as pd
from datetime import datetime
from datasets import Dataset, DatasetDict, Features, Value, GeneratorBasedBuilder, Split

_DESCRIPTION = """\
Qubit Historical Data - Comprehensive cryptocurrency OHLCV data from Binance,
including both spot and futures markets with multiple timeframes.
"""

_HOMEPAGE = "https://huggingface.co/datasets/Yllvar/qubit-historical-data"

_LICENSE = "MIT"

_FEATURES = Features({
    "timestamp": Value("timestamp[ms]"),
    "open": Value("float64"),
    "high": Value("float64"),
    "low": Value("float64"),
    "close": Value("float64"),
    "volume": Value("float64"),
    "symbol": Value("string"),
    "market_type": Value("string"),
    "timeframe": Value("string"),
    "exchange": Value("string")
})

class QubitHistoricalData(GeneratorBasedBuilder):
    """Binance historical OHLCV data for cryptocurrencies."""
    
    VERSION = "1.0.0"
    DEFAULT_CONFIG_NAME = "all"
    
    BUILDER_CONFIGS = [
        {"name": "spot", "description": "Spot market data only"},
        {"name": "futures", "description": "Futures market data only"},
        {"name": "all", "description": "All market data (spot and futures)"},
    ]

    def _info(self):
        return DatasetInfo(
            description=_DESCRIPTION,
            features=_FEATURES,
            homepage=_HOMEPAGE,
            license=_LICENSE,
        )

    def _split_generators(self, dl_manager):
        return [
            SplitGenerator(
                name=Split.TRAIN,
                gen_kwargs={
                    "data_dir": dl_manager.download(os.getcwd()) if dl_manager.is_streaming else os.getcwd()
                },
            )
        ]

    def _generate_examples(self, data_dir):
        """Generator with timestamp sorting and warning logging"""
        timestamp_warnings = {}
        
        for root, _, files in os.walk(data_dir):
            for filename in files:
                if filename.endswith('.csv'):
                    # ... (previous metadata extraction code) ...
                    
                    df = pd.read_csv(filepath)
                    df['timestamp'] = pd.to_datetime(df['timestamp'])
                    
                    # Check for and log timestamp issues
                    time_diff = df['timestamp'].diff().dt.total_seconds()
                    if (time_diff < 0).any():
                        warning_count = sum(time_diff < 0)
                        timestamp_warnings[filename] = warning_count
                        df = df.sort_values('timestamp')  # Ensure sorted output
                    
                    # Yield examples
                    for idx, row in df.iterrows():
                        yield idx, {
                            # ... (your field mappings) ...
                        }
        
        # Log warnings at the end
        if timestamp_warnings:
            print("\nTimestamp ordering warnings:")
            for file, count in timestamp_warnings.items():
                print(f"- {file}: {count} timestamp decreases found (data was auto-sorted)")

if __name__ == "__main__":
    # For local testing
    from datasets import load_dataset
    dataset = load_dataset(os.path.abspath(__file__), "all")
    print(dataset["train"][0])