Dooratre commited on
Commit
1cbfb0e
·
verified ·
1 Parent(s): d12ded8

Create ai.py

Browse files
Files changed (1) hide show
  1. ai.py +318 -0
ai.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import time
3
+ import pytz
4
+ from news import get_news_about
5
+ from datetime import datetime, timedelta
6
+ from timeframe import fetch_financial_data
7
+
8
+
9
+ def get_times():
10
+ """Get current time in different financial centers"""
11
+ # Define the time zones
12
+ greenwich_tz = pytz.timezone('GMT')
13
+ london_tz = pytz.timezone('Europe/London')
14
+ newyork_tz = pytz.timezone('America/New_York')
15
+ dubai_tz = pytz.timezone('Asia/Dubai')
16
+
17
+ # Get current UTC time
18
+ utc_now = datetime.now(pytz.utc)
19
+
20
+ # Convert to each timezone
21
+ greenwich_time = utc_now.astimezone(greenwich_tz)
22
+ london_time = utc_now.astimezone(london_tz)
23
+ newyork_time = utc_now.astimezone(newyork_tz)
24
+ dubai_time = utc_now.astimezone(dubai_tz)
25
+
26
+ # Format the times
27
+ time_format = "%Y-%m-%d %H:%M:%S %Z%z"
28
+
29
+ times = {
30
+ "Greenwich": greenwich_time.strftime(time_format),
31
+ "London": london_time.strftime(time_format),
32
+ "New York": newyork_time.strftime(time_format),
33
+ "Dubai": dubai_time.strftime(time_format)
34
+ }
35
+
36
+ return times
37
+
38
+
39
+ def capture_screenshot(url, browser_width=1280, browser_height=3000, full_page=True,
40
+ device_scale_factor=1, format="png"):
41
+ """Capture a screenshot of a webpage using the Imagy API"""
42
+ api_endpoint = "https://gcp.imagy.app/screenshot/createscreenshot"
43
+
44
+ payload = {
45
+ "url": url,
46
+ "browserWidth": browser_width,
47
+ "browserHeight": browser_height,
48
+ "fullPage": full_page,
49
+ "deviceScaleFactor": device_scale_factor,
50
+ "format": format
51
+ }
52
+
53
+ headers = {
54
+ "Content-Type": "application/json",
55
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"
56
+ }
57
+
58
+ try:
59
+ response = requests.post(api_endpoint, json=payload, headers=headers)
60
+ response.raise_for_status()
61
+ data = response.json()
62
+ return data.get("fileUrl")
63
+ except Exception as e:
64
+ print(f"Error capturing screenshot: {e}")
65
+ return None
66
+
67
+
68
+ def chat_with_ai(chat_history, temperature=0.7):
69
+ """Send chat history to AI and get response"""
70
+ url = "https://corvo-ai-xx-ry.hf.space/chat"
71
+
72
+ headers = {
73
+ "Content-Type": "application/json",
74
+ }
75
+
76
+ payload = {
77
+ "chat_history": chat_history,
78
+ "temperature": temperature,
79
+ }
80
+
81
+ max_retries = 3
82
+ retry_delay = 5
83
+
84
+ for attempt in range(max_retries):
85
+ try:
86
+ response = requests.post(url, headers=headers, json=payload, timeout=120)
87
+ response.raise_for_status()
88
+ result = response.json()
89
+ return result.get("assistant_response", "No response received.")
90
+ except Exception as e:
91
+ if attempt < max_retries - 1:
92
+ time.sleep(retry_delay)
93
+ print(f"Retry {attempt+1}: Communication error - {str(e)}")
94
+ else:
95
+ print(f"Final attempt failed: {str(e)}")
96
+
97
+ return "عذراً، واجهت مشكلة في الاتصال. يرجى المحاولة مرة أخرى لاحقاً. 🙁"
98
+
99
+
100
+ def get_forex_data(pair, timeframes=["1d", "1h"]):
101
+ """Get forex data for a specific pair and timeframes"""
102
+ data = {}
103
+
104
+ # Convert timeframes to Yahoo Finance format
105
+ timeframe_mapping = {
106
+ "1m": "1m",
107
+ "5m": "5m",
108
+ "15m": "15m",
109
+ "30m": "30m",
110
+ "1h": "60m",
111
+ "4h": "4h",
112
+ "1d": "1d"
113
+ }
114
+
115
+ # List of special symbols that don't need =X suffix
116
+ special_symbols = ["DX-Y.NYB", "GC=F", "^SPX", "WTI", "^TNX" , "^FTSE"]
117
+
118
+ for tf in timeframes:
119
+ if tf in timeframe_mapping:
120
+ yahoo_tf = timeframe_mapping[tf]
121
+
122
+ # Check if the pair is in the special symbols list
123
+ if pair in special_symbols:
124
+ yahoo_symbol = pair # Use symbol as is, without appending =X
125
+ else:
126
+ # Append =X to make it a proper Yahoo Finance forex symbol
127
+ yahoo_symbol = f"{pair}=X"
128
+
129
+ print(f"Fetching {yahoo_symbol} data for {tf} timeframe...")
130
+
131
+ # Set appropriate start date based on timeframe
132
+ if tf == "1d":
133
+ # For daily timeframe, get 7 days of data
134
+ start_date = datetime.now() - timedelta(days=7)
135
+ elif tf == "1h":
136
+ # For hourly timeframe, get 3 days of data
137
+ start_date = datetime.now() - timedelta(days=3)
138
+ else:
139
+ # Default fallback (shouldn't be needed with the current implementation)
140
+ start_date = datetime.now() - timedelta(days=5)
141
+
142
+ # Use the fetch_financial_data function from timeframe.py
143
+ result = fetch_financial_data(
144
+ symbol=yahoo_symbol,
145
+ start_date=start_date,
146
+ interval=yahoo_tf
147
+ )
148
+
149
+ if result['success']:
150
+ data[tf] = {
151
+ 'dataframe': result['data'],
152
+ 'stats': result['stats'],
153
+ 'table': result['table'],
154
+ 'meta_info': result['meta_info']
155
+ }
156
+ print(f"Successfully fetched {tf} data for {pair}")
157
+ else:
158
+ print(f"Failed to fetch {tf} data for {pair}: {result['message']}")
159
+ data[tf] = None
160
+ else:
161
+ print(f"Unsupported timeframe: {tf}")
162
+
163
+ return data
164
+
165
+
166
+ def analyze_forex_group(group, description, relationships):
167
+ """Main function to analyze a group of forex pairs with their relationships"""
168
+ print(f"Analyzing forex group: {', '.join(group)}")
169
+
170
+ # Step 1: Get current times in financial centers
171
+ market_times = get_times()
172
+ times_text = "\n".join([f"{k}: {v}" for k, v in market_times.items()])
173
+
174
+ # Step 2: Capture FinViz forex performance chart
175
+ finviz_url = "https://finviz.com/forex.ashx"
176
+ print("📸 Capturing Forex Performance Chart...")
177
+ performance_screenshot = capture_screenshot(finviz_url)
178
+ if performance_screenshot:
179
+ print(f"✅ Forex Performance Chart captured: {performance_screenshot}")
180
+ else:
181
+ print("❌ Failed to capture Forex Performance Chart")
182
+
183
+ # Prepare system prompt with market times, group context and relationships
184
+ system_prompt = f"""You are a Principal Forex Analyst specializing in technical analysis and correlation-based trading.
185
+ Your task is to analyze the entire forex group: {', '.join(group)} and identify the strongest trading opportunities within this correlated group.
186
+
187
+ 🕒 Current Market Times:
188
+ {times_text}
189
+
190
+ 📌 Group Context: {description}
191
+
192
+ 🔗 Relationship Analysis:
193
+ {relationships}
194
+
195
+ Your analysis must include the following:
196
+
197
+ 1. Current market hours and which financial centers are active now.
198
+ 2. Comprehensive group analysis showing how these correlated pairs are moving together or if there are any notable divergences.
199
+ 3. Individual analysis of each pair in the group.
200
+ 4. Key support and resistance zones for each pair.
201
+ 5. How the described relationships are reflected in the current price action.
202
+ 6. Which pairs in the group show the strongest technical patterns.
203
+ 7. Volatility and liquidity conditions across the group.
204
+ 8. Impact of upcoming news events (if any) on the group dynamics.
205
+ 9. Potential for 40 to 70 pip price movement in any of the pairs.
206
+
207
+ ---
208
+
209
+ Your response **must** follow this exact structure:
210
+
211
+ <Group Analysis>
212
+ Analyze the group as a whole, focusing on how the pairs interact according to their known correlations. Identify whether the correlations are still holding or if there are any notable divergences.
213
+ </Group Analysis>
214
+
215
+ <Individual Pair Analysis>
216
+ Provide a concise technical analysis for each pair in the group:
217
+
218
+ PAIR1:
219
+ - Current price action and technical structure
220
+ - Key levels and patterns
221
+ - Trend strength
222
+ - Potential targets
223
+
224
+ PAIR2:
225
+ - Current price action and technical structure
226
+ - Key levels and patterns
227
+ - Trend strength
228
+ - Potential targets
229
+
230
+ (Continue for the rest of the pairs in the group following the same format)
231
+ </Individual Pair Analysis>
232
+
233
+ <Best Opportunities>
234
+ Identify one or two pairs from the group that represent the strongest technical setups with a potential 40–70 pip movement. Explain why these opportunities stand out compared to other pairs in the group and how the correlation context strengthens this case.
235
+ </Best Opportunities>
236
+
237
+ <Prediction>
238
+ For each identified opportunity, clearly state:
239
+ - The expected direction (bullish/bearish)
240
+ - Specific price targets for the 40–70 pip move
241
+ - Key levels that confirm or invalidate the prediction
242
+ - Estimated timeframe for the move to develop
243
+ </Prediction>
244
+
245
+ <Trading Strategy>
246
+ Provide a strategic plan for trading the identified opportunities, including:
247
+ - Entry zones
248
+ - Stop loss considerations
249
+ - Take profit targets
250
+ - Risk management approach
251
+ - How to use other pairs in the group as confirmation tools
252
+ </Trading Strategy>
253
+
254
+ <Correlation Warning>
255
+ Highlight any potential risks or considerations when trading multiple pairs from the same correlated group.
256
+ </Correlation Warning>
257
+
258
+ <Forward>
259
+ For the strongest one or two setups identified, indicate that they must be forwarded to the Deep Analyst specialized in the 15-minute timeframe for precise entry analysis. Explain:
260
+ - Why this setup requires more detailed analysis on the 15-minute timeframe
261
+ - What patterns, breakouts, or pullbacks the analyst should look for on the lower timeframe
262
+ - Critical price zones for optimal entry with minimal risk
263
+ - How the correlation with other pairs can be used to time entries precisely
264
+ - The analyst should also consider what is happening on both the 1-hour and 1-day timeframes for each pair to understand the full context and optimize entry timing.
265
+ </Forward>
266
+
267
+ Always make sure to close tags properly (e.g., </Forward>)
268
+
269
+ 📌 Forwarding to the 15-minute timeframe analyst is crucial for:
270
+ - Finding precise entry points with minimal risk
271
+ - Identifying intraday patterns supporting the 1-hour analysis
272
+ - Timing entries during pullbacks or breakout confirmations
273
+ - Improving risk-to-reward ratio through tighter stop placement
274
+
275
+ ⚠️ This is **not** financial advice — only professional chart analysis for potential price movements.
276
+ """
277
+
278
+
279
+ # Build chat history with system prompt
280
+ chat_history = [
281
+ {"role": "system", "content": system_prompt}
282
+ ]
283
+
284
+ # Add Forex Performance screenshot
285
+ if performance_screenshot:
286
+ chat_history.append({
287
+ "role": "user",
288
+ "type": "multipart",
289
+ "content": [
290
+ {"type": "image", "url": performance_screenshot},
291
+ {"type": "text", "text": "Current Forex Relative Performance USD chart from FinViz"}
292
+ ]
293
+ })
294
+
295
+ # Get forex data for each pair and add to chat history
296
+ for pair in group:
297
+ timeframe_data = get_forex_data(pair, ["1d", "1h"])
298
+
299
+ # Add 1-day timeframe data
300
+ if timeframe_data.get("1d"):
301
+ chat_history.append({
302
+ "role": "user",
303
+ "content": f"**{pair} - Daily (1D) Timeframe Data**\n\n{timeframe_data['1d']['table']}\n\n**Stats:**\n{timeframe_data['1d']['stats']}\n\n**Meta Info:**\n{timeframe_data['1d']['meta_info']}"
304
+ })
305
+
306
+ # Add 1-hour timeframe data
307
+ if timeframe_data.get("1h"):
308
+ chat_history.append({
309
+ "role": "user",
310
+ "content": f"**{pair} - Hourly (1H) Timeframe Data**\n\n{timeframe_data['1h']['table']}\n\n**Stats:**\n{timeframe_data['1h']['stats']}\n\n**Meta Info:**\n{timeframe_data['1h']['meta_info']}"
311
+ })
312
+
313
+ # Get AI analysis
314
+ analysis = chat_with_ai(chat_history)
315
+ print(analysis)
316
+ print("Analysis complete!")
317
+
318
+ return analysis