deeper / ai.py
Dooratre's picture
Create ai.py
1cbfb0e verified
raw
history blame
11.7 kB
import requests
import time
import pytz
from news import get_news_about
from datetime import datetime, timedelta
from timeframe import fetch_financial_data
def get_times():
"""Get current time in different financial centers"""
# Define the time zones
greenwich_tz = pytz.timezone('GMT')
london_tz = pytz.timezone('Europe/London')
newyork_tz = pytz.timezone('America/New_York')
dubai_tz = pytz.timezone('Asia/Dubai')
# Get current UTC time
utc_now = datetime.now(pytz.utc)
# Convert to each timezone
greenwich_time = utc_now.astimezone(greenwich_tz)
london_time = utc_now.astimezone(london_tz)
newyork_time = utc_now.astimezone(newyork_tz)
dubai_time = utc_now.astimezone(dubai_tz)
# Format the times
time_format = "%Y-%m-%d %H:%M:%S %Z%z"
times = {
"Greenwich": greenwich_time.strftime(time_format),
"London": london_time.strftime(time_format),
"New York": newyork_time.strftime(time_format),
"Dubai": dubai_time.strftime(time_format)
}
return times
def capture_screenshot(url, browser_width=1280, browser_height=3000, full_page=True,
device_scale_factor=1, format="png"):
"""Capture a screenshot of a webpage using the Imagy API"""
api_endpoint = "https://gcp.imagy.app/screenshot/createscreenshot"
payload = {
"url": url,
"browserWidth": browser_width,
"browserHeight": browser_height,
"fullPage": full_page,
"deviceScaleFactor": device_scale_factor,
"format": format
}
headers = {
"Content-Type": "application/json",
"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"
}
try:
response = requests.post(api_endpoint, json=payload, headers=headers)
response.raise_for_status()
data = response.json()
return data.get("fileUrl")
except Exception as e:
print(f"Error capturing screenshot: {e}")
return None
def chat_with_ai(chat_history, temperature=0.7):
"""Send chat history to AI and get response"""
url = "https://corvo-ai-xx-ry.hf.space/chat"
headers = {
"Content-Type": "application/json",
}
payload = {
"chat_history": chat_history,
"temperature": temperature,
}
max_retries = 3
retry_delay = 5
for attempt in range(max_retries):
try:
response = requests.post(url, headers=headers, json=payload, timeout=120)
response.raise_for_status()
result = response.json()
return result.get("assistant_response", "No response received.")
except Exception as e:
if attempt < max_retries - 1:
time.sleep(retry_delay)
print(f"Retry {attempt+1}: Communication error - {str(e)}")
else:
print(f"Final attempt failed: {str(e)}")
return "عذراً، واجهت مشكلة في الاتصال. يرجى المحاولة مرة أخرى لاحقاً. 🙁"
def get_forex_data(pair, timeframes=["1d", "1h"]):
"""Get forex data for a specific pair and timeframes"""
data = {}
# Convert timeframes to Yahoo Finance format
timeframe_mapping = {
"1m": "1m",
"5m": "5m",
"15m": "15m",
"30m": "30m",
"1h": "60m",
"4h": "4h",
"1d": "1d"
}
# List of special symbols that don't need =X suffix
special_symbols = ["DX-Y.NYB", "GC=F", "^SPX", "WTI", "^TNX" , "^FTSE"]
for tf in timeframes:
if tf in timeframe_mapping:
yahoo_tf = timeframe_mapping[tf]
# Check if the pair is in the special symbols list
if pair in special_symbols:
yahoo_symbol = pair # Use symbol as is, without appending =X
else:
# Append =X to make it a proper Yahoo Finance forex symbol
yahoo_symbol = f"{pair}=X"
print(f"Fetching {yahoo_symbol} data for {tf} timeframe...")
# Set appropriate start date based on timeframe
if tf == "1d":
# For daily timeframe, get 7 days of data
start_date = datetime.now() - timedelta(days=7)
elif tf == "1h":
# For hourly timeframe, get 3 days of data
start_date = datetime.now() - timedelta(days=3)
else:
# Default fallback (shouldn't be needed with the current implementation)
start_date = datetime.now() - timedelta(days=5)
# Use the fetch_financial_data function from timeframe.py
result = fetch_financial_data(
symbol=yahoo_symbol,
start_date=start_date,
interval=yahoo_tf
)
if result['success']:
data[tf] = {
'dataframe': result['data'],
'stats': result['stats'],
'table': result['table'],
'meta_info': result['meta_info']
}
print(f"Successfully fetched {tf} data for {pair}")
else:
print(f"Failed to fetch {tf} data for {pair}: {result['message']}")
data[tf] = None
else:
print(f"Unsupported timeframe: {tf}")
return data
def analyze_forex_group(group, description, relationships):
"""Main function to analyze a group of forex pairs with their relationships"""
print(f"Analyzing forex group: {', '.join(group)}")
# Step 1: Get current times in financial centers
market_times = get_times()
times_text = "\n".join([f"{k}: {v}" for k, v in market_times.items()])
# Step 2: Capture FinViz forex performance chart
finviz_url = "https://finviz.com/forex.ashx"
print("📸 Capturing Forex Performance Chart...")
performance_screenshot = capture_screenshot(finviz_url)
if performance_screenshot:
print(f"✅ Forex Performance Chart captured: {performance_screenshot}")
else:
print("❌ Failed to capture Forex Performance Chart")
# Prepare system prompt with market times, group context and relationships
system_prompt = f"""You are a Principal Forex Analyst specializing in technical analysis and correlation-based trading.
Your task is to analyze the entire forex group: {', '.join(group)} and identify the strongest trading opportunities within this correlated group.
🕒 Current Market Times:
{times_text}
📌 Group Context: {description}
🔗 Relationship Analysis:
{relationships}
Your analysis must include the following:
1. Current market hours and which financial centers are active now.
2. Comprehensive group analysis showing how these correlated pairs are moving together or if there are any notable divergences.
3. Individual analysis of each pair in the group.
4. Key support and resistance zones for each pair.
5. How the described relationships are reflected in the current price action.
6. Which pairs in the group show the strongest technical patterns.
7. Volatility and liquidity conditions across the group.
8. Impact of upcoming news events (if any) on the group dynamics.
9. Potential for 40 to 70 pip price movement in any of the pairs.
---
Your response **must** follow this exact structure:
<Group Analysis>
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.
</Group Analysis>
<Individual Pair Analysis>
Provide a concise technical analysis for each pair in the group:
PAIR1:
- Current price action and technical structure
- Key levels and patterns
- Trend strength
- Potential targets
PAIR2:
- Current price action and technical structure
- Key levels and patterns
- Trend strength
- Potential targets
(Continue for the rest of the pairs in the group following the same format)
</Individual Pair Analysis>
<Best Opportunities>
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.
</Best Opportunities>
<Prediction>
For each identified opportunity, clearly state:
- The expected direction (bullish/bearish)
- Specific price targets for the 40–70 pip move
- Key levels that confirm or invalidate the prediction
- Estimated timeframe for the move to develop
</Prediction>
<Trading Strategy>
Provide a strategic plan for trading the identified opportunities, including:
- Entry zones
- Stop loss considerations
- Take profit targets
- Risk management approach
- How to use other pairs in the group as confirmation tools
</Trading Strategy>
<Correlation Warning>
Highlight any potential risks or considerations when trading multiple pairs from the same correlated group.
</Correlation Warning>
<Forward>
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:
- Why this setup requires more detailed analysis on the 15-minute timeframe
- What patterns, breakouts, or pullbacks the analyst should look for on the lower timeframe
- Critical price zones for optimal entry with minimal risk
- How the correlation with other pairs can be used to time entries precisely
- 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.
</Forward>
Always make sure to close tags properly (e.g., </Forward>)
📌 Forwarding to the 15-minute timeframe analyst is crucial for:
- Finding precise entry points with minimal risk
- Identifying intraday patterns supporting the 1-hour analysis
- Timing entries during pullbacks or breakout confirmations
- Improving risk-to-reward ratio through tighter stop placement
⚠️ This is **not** financial advice — only professional chart analysis for potential price movements.
"""
# Build chat history with system prompt
chat_history = [
{"role": "system", "content": system_prompt}
]
# Add Forex Performance screenshot
if performance_screenshot:
chat_history.append({
"role": "user",
"type": "multipart",
"content": [
{"type": "image", "url": performance_screenshot},
{"type": "text", "text": "Current Forex Relative Performance USD chart from FinViz"}
]
})
# Get forex data for each pair and add to chat history
for pair in group:
timeframe_data = get_forex_data(pair, ["1d", "1h"])
# Add 1-day timeframe data
if timeframe_data.get("1d"):
chat_history.append({
"role": "user",
"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']}"
})
# Add 1-hour timeframe data
if timeframe_data.get("1h"):
chat_history.append({
"role": "user",
"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']}"
})
# Get AI analysis
analysis = chat_with_ai(chat_history)
print(analysis)
print("Analysis complete!")
return analysis