Spaces:
Sleeping

marketwise / cli.py
MikeZhang69
Configure HF Spaces: LFS for db, ignore venv
e7cf9be
Raw History Blame Contribute Delete
4.48 kB
#!/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()