import os import requests from flask import Flask, jsonify, request, send_from_directory app = Flask(__name__, static_folder='static') # Get API keys from environment variables ALPHA_VANTAGE_API_KEY = os.environ.get('ALPHA_VANTAGE_API_KEY', '') FINNHUB_API_KEY = os.environ.get('FINNHUB_API_KEY', '') GEMINI_API_KEY = os.environ.get('GEMINI_API_KEY', '') @app.route('/') def index(): return send_from_directory('static', 'index.html') @app.route('/api/ticker') def get_ticker_data(): """Get stock ticker data from Alpha Vantage""" symbols = request.args.get('symbols', 'AAPL,NVDA,ASML,INTC').split(',') results = [] for symbol in symbols: try: url = f"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={symbol}&apikey={ALPHA_VANTAGE_API_KEY}" response = requests.get(url) data = response.json() if "Global Quote" in data and data["Global Quote"]: quote = data["Global Quote"] price = float(quote.get("05. price", 0)) change_percent = quote.get("10. change percent", "0%").replace('%', '') change_direction = "up" if float(change_percent) >= 0 else "down" results.append({ "symbol": symbol, "price": price, "change_percent": abs(float(change_percent)), "direction": change_direction }) else: # Fallback to default values if API fails results.append({ "symbol": symbol, "price": 100.00, "change_percent": 1.0, "direction": "up" }) except Exception as e: print(f"Error fetching data for {symbol}: {str(e)}") # Return default values on error results.append({ "symbol": symbol, "price": 100.00, "change_percent": 1.0, "direction": "up" }) return jsonify(results) @app.route('/api/market_overview') def get_market_overview(): """Get market overview data from Finnhub""" try: url = f"https://finnhub.io/api/v1/quote?symbol=SPY&token={FINNHUB_API_KEY}" response = requests.get(url) data = response.json() return jsonify({ "market_status": "open" if data.get("t", 0) > 0 else "closed", "spy_price": data.get("c", 0), "spy_change": data.get("dp", 0) }) except Exception as e: print(f"Error fetching market overview: {str(e)}") return jsonify({ "market_status": "open", "spy_price": 470.00, "spy_change": 0.5 }) @app.route('/api/economic_calendar') def get_economic_calendar(): """Get economic calendar from Finnhub""" try: # Current date in YYYY-MM-DD format from datetime import datetime, timedelta today = datetime.now().strftime('%Y-%m-%d') next_week = (datetime.now() + timedelta(days=7)).strftime('%Y-%m-%d') url = f"https://finnhub.io/api/v1/calendar/economic?from={today}&to={next_week}&token={FINNHUB_API_KEY}" response = requests.get(url) data = response.json() # Process and simplify the data events = [] if "economicCalendar" in data: for event in data["economicCalendar"][:15]: # Limit to 15 events events.append({ "country": event.get("country", ""), "event": event.get("event", ""), "time": event.get("time", ""), "impact": event.get("impact", "low"), "forecast": event.get("forecast", ""), "previous": event.get("previous", "") }) return jsonify(events) except Exception as e: print(f"Error fetching economic calendar: {str(e)}") return jsonify([]) @app.route('/api/market_data/') def get_market_data(market): """Get market data for specific regions""" try: symbols = { "asia": ["^N225", "000001.SS", "^HSI", "^AXJO"], "europe": ["^GDAXI", "^FTSE", "^FCHI", "^STOXX50E"], "us": ["^GSPC", "^IXIC", "^DJI", "^VIX"] } if market not in symbols: return jsonify([]) results = [] for symbol in symbols[market]: url = f"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={symbol}&apikey={ALPHA_VANTAGE_API_KEY}" response = requests.get(url) data = response.json() if "Global Quote" in data and data["Global Quote"]: quote = data["Global Quote"] price = float(quote.get("05. price", 0)) change_percent = quote.get("10. change percent", "0%").replace('%', '') change_direction = "up" if float(change_percent) >= 0 else "down" # Map symbol to readable name name_map = { "^N225": "Nikkei 225", "000001.SS": "Shanghai Composite", "^HSI": "Hang Seng", "^AXJO": "ASX 200", "^GDAXI": "DAX", "^FTSE": "FTSE 100", "^FCHI": "CAC 40", "^STOXX50E": "EURO STOXX 50", "^GSPC": "S&P 500", "^IXIC": "NASDAQ", "^DJI": "Dow Jones", "^VIX": "VIX" } results.append({ "name": name_map.get(symbol, symbol), "price": price, "change_percent": abs(float(change_percent)), "direction": change_direction }) else: # Fallback to default values results.append({ "name": symbol, "price": 100.00, "change_percent": 1.0, "direction": "up" }) return jsonify(results) except Exception as e: print(f"Error fetching data for {market}: {str(e)}") return jsonify([]) @app.route('/api/gemini_key') def get_gemini_key(): """Return a masked version of the Gemini API key for verification""" if GEMINI_API_KEY: # Return only first 4 chars and mask the rest for verification masked_key = GEMINI_API_KEY[:4] + '*' * (len(GEMINI_API_KEY) - 4) return jsonify({"status": "available", "key": masked_key}) else: return jsonify({"status": "unavailable", "key": ""}) @app.route('/api/intermarket') def get_intermarket_data(): """Get intermarket analysis data""" try: # Get data for stocks, bonds, commodities, and forex indices = ["SPY", "TLT", "GLD", "UUP"] results = {} for idx in indices: url = f"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={idx}&apikey={ALPHA_VANTAGE_API_KEY}" response = requests.get(url) data = response.json() if "Global Quote" in data and data["Global Quote"]: quote = data["Global Quote"] price = float(quote.get("05. price", 0)) change_percent = quote.get("10. change percent", "0%").replace('%', '') results[idx] = { "price": price, "change_percent": float(change_percent.replace('%', '')) } # Calculate simplified correlations (simulated) correlations = { "stocks_bonds": 0.68, "stocks_commodities": -0.42, "stocks_dollar": 0.12, "bonds_commodities": -0.71, "bonds_dollar": -0.53, "commodities_dollar": -0.65 } return jsonify({ "assets": results, "correlations": correlations }) except Exception as e: print(f"Error fetching intermarket data: {str(e)}") return jsonify({"assets": {}, "correlations": {}}) @app.route('/api/affirmations//') def get_affirmation(category, status): """Get a specific affirmation based on category and status""" affirmations = { 'discipline': { 'preparing': 'Ich bin ein disziplinierter und geduldiger Trader, der seinem Handelsplan mit unerschütterlichem Engagement folgt. Ich vertraue auf die Wirksamkeit meiner Strategien und warte geduldig auf Setups mit hoher Wahrscheinlichkeit.', 'active': 'Während mein Trade aktiv ist, bleibe ich diszipliniert und geduldig. Ich folge meinem Plan und erlaube keiner Emotion, meine Strategie zu untergraben.', 'developing': 'Beim Entwickeln meiner Strategie wende ich Disziplin und Geduld an. Ich nehme mir die Zeit, jedes Detail zu durchdenken und teste gründlich, bevor ich handele.', 'break': 'In dieser Pause pflege ich meine Disziplin und Geduld, indem ich reflektiere und lerne. Ich verstehe, dass Ruhezeiten wesentlich für nachhaltigen Trading-Erfolg sind.' }, 'abundance': { 'preparing': 'Ich ziehe reichlich Handelsmöglichkeiten an, die mit meiner Strategie übereinstimmen. Der Markt bietet einen endlosen Strom von Gelegenheiten, und ich bin bereit, sie zu nutzen.', 'active': 'Mein aktueller Trade ist eine von vielen Gelegenheiten für Wohlstand. Ich denke in Fülle und weiß, dass unabhängig vom Ausgang dieses Trades weitere profitable Chancen folgen werden.', 'developing': 'Ich entwickle meine Strategie mit einer Überfluss-Denkweise. Ich erkenne die unbegrenzten Möglichkeiten des Marktes an und erschaffe einen Ansatz, der diesen Reichtum anzieht.', 'break': 'Während dieser Pause ziehe ich neue Erkenntnisse und Möglichkeiten an. Ich nutze diese Zeit, um meine Überfluss-Denkweise zu stärken und mich auf neue Handelschancen vorzubereiten.' } # Additional categories could be added here } if category in affirmations and status in affirmations[category]: return jsonify({ 'text': affirmations[category][status], 'category': category, 'status': status }) else: return jsonify({ 'text': 'Ich handle mit Klarheit, Disziplin und Vertrauen.', 'category': 'general', 'status': 'default' }) if __name__ == '__main__': app.run(host='0.0.0.0', port=7860, debug=True)