Spaces:
Sleeping
Sleeping
| #!/usr/bin/env python3 | |
| """ | |
| Standalone script to fetch Kalshi menu data and export as JSON. | |
| Run this on your local machine to fetch data from Kalshi's public API. | |
| Usage: | |
| python fetch_kalshi_menu.py [--num-items N] [--output output.json] | |
| Examples: | |
| python fetch_kalshi_menu.py | |
| python fetch_kalshi_menu.py --num-items 15 --output kalshi_data.json | |
| python fetch_kalshi_menu.py --verbose | |
| """ | |
| import argparse | |
| import json | |
| import sys | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| # Import the generator from kalshi_data.py | |
| from kalshi_data import KalshiDataGenerator | |
| def main(): | |
| parser = argparse.ArgumentParser( | |
| description="Fetch Kalshi menu data and export as JSON" | |
| ) | |
| parser.add_argument( | |
| "--num-items", | |
| type=int, | |
| default=10, | |
| help="Number of items per section (default: 10)", | |
| ) | |
| parser.add_argument( | |
| "--output", | |
| type=str, | |
| default="kalshi_menu_data.json", | |
| help="Output JSON file path (default: kalshi_menu_data.json)", | |
| ) | |
| parser.add_argument( | |
| "--verbose", | |
| action="store_true", | |
| help="Print detailed menu output during fetch", | |
| ) | |
| args = parser.parse_args() | |
| print("🚀 Starting Kalshi menu data fetch...") | |
| print(f" Items per section: {args.num_items}") | |
| print(f" Output file: {args.output}") | |
| print() | |
| try: | |
| # Create generator instance | |
| generator = KalshiDataGenerator(num_items=args.num_items) | |
| # Build menu (this fetches all data) | |
| print("📊 Fetching menu data from Kalshi API...") | |
| menu_entries = generator.build_menu(verbose=args.verbose) | |
| # Format as MenuResponse structure | |
| menu_response = { | |
| "generated_at": datetime.now(timezone.utc).isoformat(), | |
| "source": "Kalshi API", | |
| "api_base": "https://api.elections.kalshi.com/trade-api/v2", | |
| "items": menu_entries, | |
| } | |
| # Write to JSON file | |
| output_path = Path(args.output) | |
| with open(output_path, "w", encoding="utf-8") as f: | |
| json.dump(menu_response, f, indent=2, ensure_ascii=False) | |
| print() | |
| print(f"✅ Success! Menu data exported to: {output_path}") | |
| print(f" Total items: {len(menu_entries)}") | |
| # Show breakdown by category | |
| categories = {} | |
| for item in menu_entries: | |
| cat = item.get("category", "unknown") | |
| categories[cat] = categories.get(cat, 0) + 1 | |
| print(" Breakdown by section:") | |
| for cat, count in categories.items(): | |
| print(f" • {cat}: {count} items") | |
| return 0 | |
| except KeyboardInterrupt: | |
| print("\n⚠️ Interrupted by user") | |
| return 1 | |
| except Exception as e: | |
| print(f"\n❌ Error: {e}", file=sys.stderr) | |
| import traceback | |
| traceback.print_exc() | |
| return 1 | |
| if __name__ == "__main__": | |
| sys.exit(main()) |