File size: 6,627 Bytes
0ff4a53 b0d7d58 e491829 0ff4a53 bfefae6 0ff4a53 7372484 0ff4a53 2a061bb 0ff4a53 2f66343 00b8ce2 0ff4a53 2a061bb 0ff4a53 2a061bb 0ff4a53 2a061bb b0d7d58 e491829 9c5bb0c b0d7d58 9c5bb0c b0d7d58 9c5bb0c 85aab5e edc1af6 85aab5e 0ff4a53 85aab5e 0ff4a53 85aab5e 0ff4a53 b57258a 0ff4a53 6feb8f6 cf002fc e60e5d9 00b8ce2 0ff4a53 |
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 |
import gradio as gr
from huggingface_hub import InferenceClient
import google.generativeai as genai
import numpy as np
import PIL.Image
import io, os
"""
For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
"""
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
genai.configure(api_key='AIzaSyAtdSFdZ2WZv2TmJYijVz286JBX7HpddQk')
def respond(
message,
history: list[tuple[str, str]],
image,
):
messages = ""
if message == "Analyze":
message = (
"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"
"Candlestick Analysis: Spot and describe any notable candlestick formations.\n"
"Other Indicator Analysis: Include analysis of additional technical indicators present on the chart.\n"
"Additional Observations: Note any other important observations made from the chart.\n\n"
"Example Analysis Structure:\n\n"
"Trend Analysis:\n"
"The stock is currently in a strong bullish trend, evidenced by higher highs and higher lows over the past X timesteps.\n\n"
"Price Action:\n"
"Recent price action shows a breakout from a key resistance level at $Y, indicating strong upward momentum.\n\n"
"Entry Point:\n"
"Enter the trade at $Z, where the breakout is confirmed.\n\n"
"Exit Point:\n"
"Exit the trade at $A, near the next major resistance level, for a potential profit of $B per share.\n\n"
"Hold Conditions:\n"
"Hold the position as long as the price remains above the support level at $C.\n\n"
"Risk Management:\n"
"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\n"
"Timeframe:\n"
"The expected duration of the trade is F timesteps, aiming for a profit of $G in this period.\n\n"
"Candlestick Analysis:\n"
"Spot and describe any significant candlestick patterns, such as doji, hammer, or engulfing patterns, and their implications for the trade.\n\n"
"Other Indicator Analysis:\n"
"Evaluate additional technical indicators present on the chart, such as moving averages, RSI, MACD, or Bollinger Bands, and discuss how they support the trading strategy.\n\n"
"Additional Observations:\n"
"Note any other relevant observations, such as volume spikes, unusual price gaps, or divergence patterns, that could impact the trade's success.\n\n"
"By including these detailed elements, the analysis will provide a comprehensive and actionable trading strategy based on the stock chart's data."
)
else:
message = f"Act as a genius Trader and answer the following request: {message} after analyzing the chart thoroughly."
for val in history:
if val[0]:
messages += "{'role': 'user', 'content': "+val[0]+"}"
if val[1]:
messages += "{'role': 'user', 'content': "+val[1]+"}"
messages += "{'role': 'user', 'content': "+message+"}"
print (messages,image)
## for image
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")
## for image
response = model.generate_content([messages, img])
try:
response = model.generate_content([messages, 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()}**\n"
else:
formatted_response += line + "\n"
return formatted_response
except ValueError as e:
return f"Error in generating response: {e}"
# response = ""
# for message in client.chat_completion(
# messages,
# max_tokens=max_tokens,
# stream=True,
# temperature=temperature,
# top_p=top_p,
# ):
# token = message.choices[0].delta.content
# response += token
# yield response
"""
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
"""
demo = gr.ChatInterface(
respond,
additional_inputs=[
gr.Image(show_label=False)
],
additional_inputs_accordion=gr.Accordion(open=True),
theme=gr.themes.Soft(),
retry_btn=None,
undo_btn=None,
clear_btn=None,
)
if __name__ == "__main__":
demo.launch() |