sohoso commited on
Commit
55a12d6
·
verified ·
1 Parent(s): 3e30424

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -53
app.py CHANGED
@@ -2,11 +2,11 @@ import google.generativeai as genai
2
  import gradio as gr
3
  import numpy as np
4
  import PIL.Image
5
- import re
6
 
7
  genai.configure(api_key="AIzaSyAj-b3sO_wUguMdpXWScxKzMHxb8C5cels")
8
 
9
- def ImageChat(image):
10
  # Check image file and convert to a PIL Image object
11
  if isinstance(image, np.ndarray):
12
  img = PIL.Image.fromarray(image)
@@ -16,68 +16,60 @@ def ImageChat(image):
16
  except (AttributeError, IOError) as e:
17
  return f"Invalid image provided. Please provide a valid image file. Error: {e}"
18
 
19
- # Custom prompt
20
- custom_prompt = """
21
- 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.
22
-
23
- Key Elements to Include:
24
-
25
- **Trend Analysis:** Identify the current trend and its strength (e.g., bullish, bearish, consolidation).
26
- **Price Action:** Describe recent price movements and patterns (e.g., support and resistance levels, candlestick patterns).
27
- **Entry and Exit Points:** Specify precise entry and exit points based on the chart’s data.
28
- **Hold Conditions:** Determine the conditions under which holding the position is advisable.
29
- **Risk Management:** Outline stop-loss levels, position sizing, and other risk management techniques.
30
- **Timeframe:** Indicate the expected duration of the trade in terms of the chart’s timesteps, balancing profit potential with trade duration.
31
- **Profit Potential:** Estimate the potential profit in absolute values as shown in the chart.
32
- Example Analysis Structure:
33
-
34
- **Trend Analysis:** The stock is currently in a strong bullish trend, evidenced by higher highs and higher lows over the past **X** timesteps.
35
- **Price Action:** Recent price action shows a breakout from a key resistance level at **$Y**, indicating strong upward momentum.
36
- **Entry Point:** Enter the trade at **$Z**, where the breakout is confirmed.
37
- **Exit Point:** Exit the trade at **$A**, near the next major resistance level, for a potential profit of **$B** per share.
38
- **Hold Conditions:** Hold the position as long as the price remains above the support level at **$C**.
39
- **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.
40
- **Timeframe:** The expected duration of the trade is **F** timesteps, aiming for a profit of **$G** in this period.
41
- """
42
-
43
  # Load model
44
  model = genai.GenerativeModel("gemini-pro-vision")
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  # Generate response
47
  try:
48
  response = model.generate_content([custom_prompt, img])
49
  if not response or not response.text:
50
  return "No valid response received. The response might have been blocked."
51
-
52
- # Apply rich formatting to the response
53
- formatted_response = response.text
54
- for title in ["Trend Analysis", "Price Action", "Entry Point", "Exit Point", "Hold Conditions", "Risk Management", "Timeframe", "Profit Potential"]:
55
- formatted_response = formatted_response.replace(title, f"**{title.upper()}**")
56
- formatted_response = re.sub(r"(\d+\.?\d*)", r"**\1**", formatted_response)
57
- formatted_response = formatted_response.replace('\n', '\n\n')
 
 
58
  return formatted_response
59
  except ValueError as e:
60
  return f"Error in generating response: {e}"
61
 
62
- # Define the Gradio interface
63
- with gr.Blocks() as app:
64
- gr.Markdown("# Image Chat")
65
- image_input = gr.Image(label="Image")
66
- analyze_button = gr.Button("Analyze", elem_id="analyze_button")
67
- prompt_input = gr.Textbox(label="Prompt", value="Analyze the attached stock chart image as a technical quant analyst...")
68
- response_output = gr.Textbox(label="Response")
69
-
70
- def analyze_image(image):
71
- return ImageChat(image)
72
-
73
- analyze_button.click(fn=analyze_image, inputs=image_input, outputs=response_output)
74
-
75
- # Style the analyze button
76
- app.css = """
77
- #analyze_button {
78
- background-color: #26de81;
79
- color: #ffffff;
80
- }
81
- """
82
 
83
  app.launch()
 
2
  import gradio as gr
3
  import numpy as np
4
  import PIL.Image
5
+ import io
6
 
7
  genai.configure(api_key="AIzaSyAj-b3sO_wUguMdpXWScxKzMHxb8C5cels")
8
 
9
+ def ImageChat(image, prompt="Analyze"):
10
  # Check image file and convert to a PIL Image object
11
  if isinstance(image, np.ndarray):
12
  img = PIL.Image.fromarray(image)
 
16
  except (AttributeError, IOError) as e:
17
  return f"Invalid image provided. Please provide a valid image file. Error: {e}"
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  # Load model
20
  model = genai.GenerativeModel("gemini-pro-vision")
21
 
22
+ # Custom prompt
23
+ custom_prompt = (
24
+ "Analyze the attached stock chart image as a technical quant analyst. Based on the trend, "
25
+ "movement, and price action visible in the chart, make intelligent and substantial trading suggestions. "
26
+ "Provide clear entry, exit, and hold conditions, along with detailed risk management strategies. Discuss the "
27
+ "expected timeframe for the trade, specifying the duration in terms of the timesteps shown in the chart. Aim for "
28
+ "a good profit-to-time ratio, favoring high profits within shorter timeframes unless longer timeframes yield "
29
+ "significantly higher profits. Reference absolute values from the chart rather than relying on general strategies. "
30
+ "Avoid basic explanations of indicators, and focus on providing in-depth analysis.\n\n"
31
+ "**Key Elements to Include:**\n\n"
32
+ "**Trend Analysis:** Identify the current trend and its strength (e.g., bullish, bearish, consolidation).\n"
33
+ "**Price Action:** Describe recent price movements and patterns (e.g., support and resistance levels, candlestick patterns).\n"
34
+ "**Entry and Exit Points:** Specify precise entry and exit points based on the chart’s data.\n"
35
+ "**Hold Conditions:** Determine the conditions under which holding the position is advisable.\n"
36
+ "**Risk Management:** Outline stop-loss levels, position sizing, and other risk management techniques.\n"
37
+ "**Timeframe:** Indicate the expected duration of the trade in terms of the chart’s timesteps, balancing profit potential with trade duration.\n"
38
+ "**Profit Potential:** Estimate the potential profit in absolute values as shown in the chart.\n\n"
39
+ "Example Analysis Structure:\n\n"
40
+ "**Trend Analysis:** The stock is currently in a strong bullish trend, evidenced by higher highs and higher lows over the past **X** timesteps. 📈\n"
41
+ "**Price Action:** Recent price action shows a breakout from a key resistance level at **$Y**, indicating strong upward momentum. 💹\n"
42
+ "**Entry Point:** Enter the trade at **$Z**, where the breakout is confirmed. 🔍\n"
43
+ "**Exit Point:** Exit the trade at **$A**, near the next major resistance level, for a potential profit of **$B** per share. 💵\n"
44
+ "**Hold Conditions:** Hold the position as long as the price remains above the support level at **$C**.\n"
45
+ "**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"
46
+ "**Timeframe:** The expected duration of the trade is **F** timesteps, aiming for a profit of **$G** in this period. ⏳\n"
47
+ )
48
+
49
  # Generate response
50
  try:
51
  response = model.generate_content([custom_prompt, img])
52
  if not response or not response.text:
53
  return "No valid response received. The response might have been blocked."
54
+
55
+ # Formatting the response
56
+ formatted_response = ""
57
+ for line in response.text.split("\n"):
58
+ if line.strip().endswith(":"):
59
+ formatted_response += f"**{line.strip().upper()}**\n"
60
+ else:
61
+ formatted_response += line.replace("$", "**$").replace(" ", "** ").replace("** ", "**")
62
+
63
  return formatted_response
64
  except ValueError as e:
65
  return f"Error in generating response: {e}"
66
 
67
+ app = gr.Interface(
68
+ fn=ImageChat,
69
+ inputs=[gr.Image(label="Image"), gr.Text(label="Prompt", default="Analyze")],
70
+ outputs=gr.Text(label="Response"),
71
+ title="Trading View Chat Analyzer",
72
+ theme=gr.themes.Soft()
73
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
  app.launch()