import google.generativeai as genai import gradio as gr import numpy as np import PIL.Image import io genai.configure(api_key="AIzaSyAj-b3sO_wUguMdpXWScxKzMHxb8C5cels") def ImageChat(image, prompt="Analyze"): # Check image file and convert to a PIL Image object if isinstance(image, np.ndarray): img = PIL.Image.fromarray(image) else: try: img = PIL.Image.open(image) except (AttributeError, IOError) as e: return f"Invalid image provided. Please provide a valid image file. Error: {e}" # Load model model = genai.GenerativeModel("gemini-pro-vision") # Custom prompt custom_prompt = ( "Analyze the attached stock chart image as a technical quant analyst. Based on the trend, " "movement, and price action visible in the chart, make intelligent and substantial trading suggestions. " "Provide clear entry, exit, and hold conditions, along with detailed risk management strategies. Discuss the " "expected timeframe for the trade, specifying the duration in terms of the timesteps shown in the chart. Aim for " "a good profit-to-time ratio, favoring high profits within shorter timeframes unless longer timeframes yield " "significantly higher profits. Reference absolute values from the chart rather than relying on general strategies. " "Avoid basic explanations of indicators, and focus on providing in-depth analysis.\n\n" "**Key Elements to Include:**\n\n" "**Trend Analysis:** Identify the current trend and its strength (e.g., bullish, bearish, consolidation).\n" "**Price Action:** Describe recent price movements and patterns (e.g., support and resistance levels, candlestick patterns).\n" "**Entry and Exit Points:** Specify precise entry and exit points based on the chart’s data.\n" "**Hold Conditions:** Determine the conditions under which holding the position is advisable.\n" "**Risk Management:** Outline stop-loss levels, position sizing, and other risk management techniques.\n" "**Timeframe:** Indicate the expected duration of the trade in terms of the chart’s timesteps, balancing profit potential with trade duration.\n" "**Profit Potential:** Estimate the potential profit in absolute values as shown in the chart.\n\n" "Example Analysis Structure:\n\n" "**Trend Analysis:** The stock is currently in a strong bullish trend, evidenced by higher highs and higher lows over the past **X** timesteps. 📈\n" "**Price Action:** Recent price action shows a breakout from a key resistance level at **$Y**, indicating strong upward momentum. 💹\n" "**Entry Point:** Enter the trade at **$Z**, where the breakout is confirmed. 🔍\n" "**Exit Point:** Exit the trade at **$A**, near the next major resistance level, for a potential profit of **$B** per share. 💵\n" "**Hold Conditions:** Hold the position as long as the price remains above the support level at **$C**.\n" "**Risk Management:** Set a stop-loss at **$D** to limit potential losses to **$E** per share, and use position sizing to ensure the total risk is within acceptable limits. 🚨\n" "**Timeframe:** The expected duration of the trade is **F** timesteps, aiming for a profit of **$G** in this period. ⏳\n" ) # Generate response try: response = model.generate_content([custom_prompt, img]) if not response or not response.text: return "No valid response received. The response might have been blocked." # Formatting the response formatted_response = "" for line in response.text.split("\n"): if line.strip().endswith(":"): formatted_response += f"**{line.strip().upper()}**\n" else: formatted_response += line.replace("$", "**$").replace(" ", "** ").replace("** ", "**") return formatted_response except ValueError as e: return f"Error in generating response: {e}" app = gr.Interface( fn=ImageChat, inputs=[gr.Image(label="Image"), gr.Text(label="Prompt", default="Analyze")], outputs=gr.Text(label="Response"), title="Trading View Chat Analyzer", theme=gr.themes.Soft() ) app.launch()