File size: 10,818 Bytes
d57b46c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
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/<market>')
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/<category>/<status>')
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)