File size: 7,133 Bytes
c49b21b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Crypto Symbol Normalizer
========================

Provides consistent symbol normalization across all data fetchers and mergers.
This ensures that different representations of the same cryptocurrency (e.g., XRP vs ripple)
are treated consistently throughout the entire pipeline.

Features:
- Maps various symbol formats to canonical identifiers
- Supports both short symbols (BTC, ETH) and long names (bitcoin, ethereum)
- Case-insensitive matching
- Logging for debugging normalization process

Author: AI Assistant
Date: August 2025
"""

import logging
from typing import Dict, List, Set

logger = logging.getLogger(__name__)

class CryptoSymbolNormalizer:
    """
    Centralized crypto symbol normalization for consistent asset identification
    """
    
    def __init__(self):
        """Initialize the symbol normalizer with predefined mappings"""
        self.symbol_mapping = self._build_symbol_mapping()
        logger.info(f"Initialized CryptoSymbolNormalizer with {len(self.symbol_mapping)} mappings")
    
    def _build_symbol_mapping(self) -> Dict[str, str]:
        """
        Build comprehensive symbol mapping dictionary
        
        Returns:
            Dictionary mapping various symbol formats to canonical slugs
        """
        # Canonical mapping for major crypto assets
        # Maps various symbols/names to the official canonical identifier
        symbol_mapping = {
            # Bitcoin variants
            'bitcoin': 'bitcoin',
            'btc': 'bitcoin',
            'Bitcoin': 'bitcoin',
            'BTC': 'bitcoin',
            
            # Ethereum variants  
            'ethereum': 'ethereum',
            'eth': 'ethereum',
            'Ethereum': 'ethereum',
            'ETH': 'ethereum',
            
            # Ripple/XRP variants (canonical: ripple for Santiment)
            'ripple': 'ripple',
            'xrp': 'ripple',
            'Ripple': 'ripple',
            'XRP': 'ripple',
            
            # Solana variants (canonical: solana for Santiment)
            'solana': 'solana',
            'sol': 'solana',
            'Solana': 'solana',
            'SOL': 'solana',
            
            # Cardano variants (canonical: cardano for Santiment)
            'cardano': 'cardano',
            'ada': 'cardano',
            'Cardano': 'cardano',
            'ADA': 'cardano',
            
            # Polkadot variants
            'polkadot': 'polkadot',
            'dot': 'polkadot',
            'Polkadot': 'polkadot',
            'DOT': 'polkadot',
            
            # Chainlink variants
            'chainlink': 'chainlink',
            'link': 'chainlink',
            'Chainlink': 'chainlink',
            'LINK': 'chainlink',
            
            # Litecoin variants
            'litecoin': 'litecoin',
            'ltc': 'litecoin',
            'Litecoin': 'litecoin',
            'LTC': 'litecoin',
            
            # Bitcoin Cash variants
            'bitcoin-cash': 'bitcoin-cash',
            'bch': 'bitcoin-cash',
            'Bitcoin Cash': 'bitcoin-cash',
            'BCH': 'bitcoin-cash',
            
            # Stellar variants
            'stellar': 'stellar',
            'xlm': 'stellar',
            'Stellar': 'stellar',
            'XLM': 'stellar',
            
            # Ethereum Classic variants
            'ethereum-classic': 'ethereum-classic',
            'etc': 'ethereum-classic',
            'Ethereum Classic': 'ethereum-classic',
            'ETC': 'ethereum-classic',
            
            # EOS variants
            'eos': 'eos',
            'EOS': 'eos',
        }
        
        return symbol_mapping
    
    def normalize(self, symbol: str) -> str:
        """
        Normalize a symbol to its canonical identifier
        
        Args:
            symbol: Symbol to normalize
            
        Returns:
            Canonical identifier
        """
        if symbol in self.symbol_mapping:
            canonical = self.symbol_mapping[symbol]
            if symbol != canonical:
                logger.debug(f"Normalized '{symbol}' -> '{canonical}'")
            return canonical
        
        # If not found in mapping, return as-is but log warning
        logger.warning(f"Unknown symbol '{symbol}' not found in normalization mapping")
        return symbol.lower()
    
    def normalize_list(self, symbols: List[str]) -> List[str]:
        """
        Normalize a list of symbols and remove duplicates
        
        Args:
            symbols: List of symbols to normalize
            
        Returns:
            List of normalized, deduplicated symbols
        """
        normalized = []
        seen = set()
        
        for symbol in symbols:
            canonical = self.normalize(symbol)
            if canonical not in seen:
                normalized.append(canonical)
                seen.add(canonical)
            else:
                logger.debug(f"Removed duplicate symbol: {symbol} (canonical: {canonical})")
        
        logger.info(f"Normalized {len(symbols)} symbols to {len(normalized)} unique canonical symbols")
        return normalized
    
    def get_all_variants(self, canonical_symbol: str) -> List[str]:
        """
        Get all known variants for a canonical symbol
        
        Args:
            canonical_symbol: The canonical symbol to find variants for
            
        Returns:
            List of all variants that map to this canonical symbol
        """
        variants = [key for key, value in self.symbol_mapping.items() 
                   if value == canonical_symbol]
        return variants
    
    def get_canonical_symbols(self) -> Set[str]:
        """
        Get set of all canonical symbols
        
        Returns:
            Set of canonical symbols
        """
        return set(self.symbol_mapping.values())
    
    def add_mapping(self, symbol: str, canonical: str):
        """
        Add a new symbol mapping
        
        Args:
            symbol: Symbol variant to add
            canonical: Canonical symbol it maps to
        """
        self.symbol_mapping[symbol] = canonical
        logger.info(f"Added new mapping: '{symbol}' -> '{canonical}'")


# Global instance for easy access
_normalizer = None

def get_normalizer() -> CryptoSymbolNormalizer:
    """
    Get the global normalizer instance (singleton pattern)
    
    Returns:
        CryptoSymbolNormalizer instance
    """
    global _normalizer
    if _normalizer is None:
        _normalizer = CryptoSymbolNormalizer()
    return _normalizer

def normalize_symbol(symbol: str) -> str:
    """
    Convenience function to normalize a single symbol
    
    Args:
        symbol: Symbol to normalize
        
    Returns:
        Canonical symbol
    """
    return get_normalizer().normalize(symbol)

def normalize_symbol_list(symbols: List[str]) -> List[str]:
    """
    Convenience function to normalize a list of symbols
    
    Args:
        symbols: List of symbols to normalize
        
    Returns:
        List of normalized symbols
    """
    return get_normalizer().normalize_list(symbols)