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, css="""#component-2{ flex-direction:row !important; } #component-3{ min-height: 100% !important; width: 50% !important; } #component-6{ width: 50% !important; position: absolute !important; left: 50% !important; z-index: 100 !important; bottom: 45% !important; } #component-14{ width: 50% !important; height: 50% !important; }""" ) if __name__ == "__main__": demo.launch()