|
| 1 | +""" |
| 2 | +Alpha Vantage Data Fetcher |
| 3 | +Fetches stock quotes and data from Alpha Vantage API |
| 4 | +Returns JSON output for Rust integration |
| 5 | +""" |
| 6 | + |
| 7 | +import sys |
| 8 | +import json |
| 9 | +import os |
| 10 | +import requests |
| 11 | +from typing import Dict, Any |
| 12 | + |
| 13 | +# API Configuration |
| 14 | +API_KEY = os.environ.get('', '') |
| 15 | +BASE_URL = "https://www.alphavantage.co/query" |
| 16 | + |
| 17 | + |
| 18 | +def get_quote(symbol: str) -> Dict[str, Any]: |
| 19 | + """Fetch real-time quote for a stock symbol""" |
| 20 | + try: |
| 21 | + if not API_KEY: |
| 22 | + return {"error": "Alpha Vantage API key not configured"} |
| 23 | + |
| 24 | + params = { |
| 25 | + 'function': 'GLOBAL_QUOTE', |
| 26 | + 'symbol': symbol, |
| 27 | + 'apikey': API_KEY |
| 28 | + } |
| 29 | + |
| 30 | + response = requests.get(BASE_URL, params=params, timeout=10) |
| 31 | + response.raise_for_status() |
| 32 | + |
| 33 | + data = response.json() |
| 34 | + |
| 35 | + if 'Global Quote' not in data: |
| 36 | + return {"error": "No data returned for symbol", "symbol": symbol} |
| 37 | + |
| 38 | + quote = data['Global Quote'] |
| 39 | + |
| 40 | + result = { |
| 41 | + "symbol": symbol, |
| 42 | + "price": float(quote.get('05. price', 0)), |
| 43 | + "change": float(quote.get('09. change', 0)), |
| 44 | + "change_percent": quote.get('10. change percent', '0'), |
| 45 | + "volume": int(quote.get('06. volume', 0)), |
| 46 | + "open": float(quote.get('02. open', 0)), |
| 47 | + "high": float(quote.get('03. high', 0)), |
| 48 | + "low": float(quote.get('04. low', 0)), |
| 49 | + "previous_close": float(quote.get('08. previous close', 0)), |
| 50 | + "trading_day": quote.get('07. latest trading day', '') |
| 51 | + } |
| 52 | + |
| 53 | + return result |
| 54 | + |
| 55 | + except requests.exceptions.RequestException as e: |
| 56 | + return {"error": f"Network error: {str(e)}", "symbol": symbol} |
| 57 | + except Exception as e: |
| 58 | + return {"error": str(e), "symbol": symbol} |
| 59 | + |
| 60 | + |
| 61 | +def main(): |
| 62 | + """Main CLI entry point""" |
| 63 | + if len(sys.argv) < 3: |
| 64 | + print(json.dumps({ |
| 65 | + "error": "Usage: python alphavantage_data.py quote <symbol>" |
| 66 | + })) |
| 67 | + sys.exit(1) |
| 68 | + |
| 69 | + command = sys.argv[1] |
| 70 | + symbol = sys.argv[2] |
| 71 | + |
| 72 | + if command == "quote": |
| 73 | + result = get_quote(symbol) |
| 74 | + print(json.dumps(result, indent=2)) |
| 75 | + else: |
| 76 | + print(json.dumps({"error": f"Unknown command: {command}"})) |
| 77 | + sys.exit(1) |
| 78 | + |
| 79 | + |
| 80 | +if __name__ == "__main__": |
| 81 | + main() |
0 commit comments