Spaces:
Sleeping

File size: 3,558 Bytes
e7cf9be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
SQLAlchemy models for market data storage.
"""
from sqlalchemy import Column, Integer, String, DateTime, Numeric, Index, UniqueConstraint
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import validates
from datetime import datetime
from decimal import Decimal, InvalidOperation


Base = declarative_base()


class MarketData(Base):
    """Model for storing historical market data (OHLCV)."""
    
    __tablename__ = 'market_data'
    
    id = Column(Integer, primary_key=True)
    symbol = Column(String(10), nullable=False, index=True)
    timestamp = Column(DateTime, nullable=False)
    open_price = Column(Numeric(precision=18, scale=8), nullable=False)
    high_price = Column(Numeric(precision=18, scale=8), nullable=False)
    low_price = Column(Numeric(precision=18, scale=8), nullable=False)
    close_price = Column(Numeric(precision=18, scale=8), nullable=False)
    volume = Column(Numeric(precision=20, scale=8), nullable=False)
    
    __table_args__ = (
        UniqueConstraint('symbol', 'timestamp', name='uq_symbol_timestamp'),
        Index('idx_symbol_timestamp', 'symbol', 'timestamp'),
        Index('idx_timestamp', 'timestamp'),
    )
    
    @validates('symbol')
    def validate_symbol(self, key, symbol):
        """Validate symbol format."""
        if not symbol or len(symbol) > 10:
            raise ValueError("Symbol must be 1-10 characters")
        return symbol.upper()
    
    @validates('open_price', 'high_price', 'low_price', 'close_price')
    def validate_prices(self, key, price):
        """Validate price values."""
        if price is None:
            raise ValueError(f"{key} cannot be None")
        
        # Convert to Decimal for validation with exception handling
        try:
            if isinstance(price, (int, float)):
                price = Decimal(str(price))
            elif not isinstance(price, Decimal):
                price = Decimal(str(price))
        except (ValueError, TypeError, InvalidOperation) as e:
            raise ValueError(f"Invalid {key} value: {price}. Must be a valid number.") from e
        
        if price <= 0:
            raise ValueError(f"{key} must be positive")
        return price
    
    @validates('volume')
    def validate_volume(self, key, volume):
        """Validate volume values."""
        if volume is None:
            raise ValueError("Volume cannot be None")
        
        # Convert to Decimal for validation with exception handling
        try:
            if isinstance(volume, (int, float)):
                volume = Decimal(str(volume))
            elif not isinstance(volume, Decimal):
                volume = Decimal(str(volume))
        except (ValueError, TypeError, InvalidOperation) as e:
            raise ValueError(f"Invalid volume value: {volume}. Must be a valid number.") from e
        
        if volume < 0:
            raise ValueError("Volume must be non-negative")
        return volume
    
    def __repr__(self):
        return f"<MarketData(symbol='{self.symbol}', timestamp='{self.timestamp}', close={self.close_price})>"
    
    def to_dict(self):
        """Convert model instance to dictionary."""
        return {
            'id': self.id,
            'symbol': self.symbol,
            'timestamp': self.timestamp,
            'open_price': float(self.open_price),
            'high_price': float(self.high_price),
            'low_price': float(self.low_price),
            'close_price': float(self.close_price),
            'volume': float(self.volume)
        }