Spaces:
Sleeping

File size: 4,484 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
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
#!/usr/bin/env python3
"""
MarketWise CLI - Command line interface for testing the data system.

Usage:
    python cli.py --help
    python cli.py fetch --symbol ^GSPC --days 30
    python cli.py list-symbols
    python cli.py summary
"""

import argparse
import sys
from pathlib import Path
from datetime import datetime, timedelta

# Add src to path
sys.path.append(str(Path(__file__).parent / "src"))

def setup_logging():
    """Set up logging for CLI operations."""
    import logging
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )

def fetch_data(symbol: str, days: int):
    """Fetch and store data for a symbol."""
    try:
        from src.data.storage import MarketDataStorage
        
        storage = MarketDataStorage()
        end_date = datetime.now()
        start_date = end_date - timedelta(days=days)
        
        print(f"Fetching {days} days of data for {symbol}...")
        count = storage.fetch_and_store_historical_data(symbol, start_date, end_date)
        print(f"Successfully stored {count} records for {symbol}")
        
    except ImportError as e:
        print(f"Error: Missing dependencies. Please install requirements: {e}")
    except Exception as e:
        print(f"Error fetching data: {e}")

def list_symbols():
    """List available symbols in database."""
    try:
        from src.data.storage import MarketDataStorage
        
        storage = MarketDataStorage()
        symbols = storage.get_available_symbols()
        
        if symbols:
            print("Available symbols in database:")
            for symbol in symbols:
                earliest, latest = storage.get_data_date_range(symbol)
                print(f"  {symbol}: {earliest.date()} to {latest.date()}")
        else:
            print("No symbols found in database")
            
    except ImportError as e:
        print(f"Error: Missing dependencies. Please install requirements: {e}")
    except Exception as e:
        print(f"Error listing symbols: {e}")

def show_summary():
    """Show database summary."""
    try:
        from src.data.storage import MarketDataStorage
        
        storage = MarketDataStorage()
        summary = storage.get_data_summary()
        
        print("Database Summary:")
        print(f"  Total records: {summary['total_records']}")
        print(f"  Unique symbols: {summary['unique_symbols']}")
        if summary['earliest_date']:
            print(f"  Date range: {summary['earliest_date'].date()} to {summary['latest_date'].date()}")
        else:
            print("  No data in database")
            
    except ImportError as e:
        print(f"Error: Missing dependencies. Please install requirements: {e}")
    except Exception as e:
        print(f"Error getting summary: {e}")

def show_config():
    """Show configuration."""
    try:
        from src.utils.config import Config
        
        config = Config()
        indices = config.get_indices()
        
        print("Configured Market Indices:")
        for symbol, info in indices['indices'].items():
            print(f"  {symbol}: {info['name']} ({info['market']})")
            
    except Exception as e:
        print(f"Error loading configuration: {e}")

def main():
    """Main CLI entry point."""
    parser = argparse.ArgumentParser(description="MarketWise CLI")
    subparsers = parser.add_subparsers(dest='command', help='Available commands')
    
    # Fetch command
    fetch_parser = subparsers.add_parser('fetch', help='Fetch market data')
    fetch_parser.add_argument('--symbol', required=True, help='Stock symbol (e.g., ^GSPC)')
    fetch_parser.add_argument('--days', type=int, default=30, help='Number of days to fetch')
    
    # List symbols command
    subparsers.add_parser('list-symbols', help='List available symbols')
    
    # Summary command
    subparsers.add_parser('summary', help='Show database summary')
    
    # Config command
    subparsers.add_parser('config', help='Show configuration')
    
    args = parser.parse_args()
    
    if not args.command:
        parser.print_help()
        return
    
    setup_logging()
    
    if args.command == 'fetch':
        fetch_data(args.symbol, args.days)
    elif args.command == 'list-symbols':
        list_symbols()
    elif args.command == 'summary':
        show_summary()
    elif args.command == 'config':
        show_config()

if __name__ == "__main__":
    main()