File size: 10,342 Bytes
66a4fc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4793e9e
66a4fc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# ANAL脥TICA BOUTIQUE, SC (https://www.visoresanalitica.com.mx/)
# DEMO
# 
# PROBLEM: 

# Multi-agent Collaboration for Financial Analysis
# Demostrate ways for making agents collaborate with each other.
# 

# python app.py

# Dependencies:
import gradio as gr
from crewai import Agent, Task, Crew, Process
from langchain_openai import ChatOpenAI
#from langchain_community.chat_message_histories import GradioChatMessageHistory
from langchain_community.chat_message_histories.in_memory import ChatMessageHistory
import os
import sys
import io
import pandas as pd
from crewai_tools import SerperDevTool, ScrapeWebsiteTool
#from scrape_website_tool import ScrapeWebsiteTool
#from serper_dev_tool import SerperDevTool

#
# Obtener las API keys desde .env
openai_api_key = os.getenv("OPENAI_API_KEY")
serper_api_key = os.getenv("SERPER_API_KEY")

# Obtener las API keys desde SECRETS
#openai_api_key = st.secrets["OPENAI_API_KEY"]
#serper_api_key = st.secrets["SERPER_API_KEY"]

# Define the list of models and initialize your agents and tasks as per the earlier code
MODEL_LIST = ['gpt-4o-mini', 'gpt-4o']

# crewAI Tools
search_tool = SerperDevTool()
scrape_tool = ScrapeWebsiteTool()

# Define Gradio interface components
def execute_financial_analysis( stock_selection, model_option, initial_capital, risk_tolerance, trading_strategy_preference ):
    sys.stdout = io.StringIO()  # Capture output to display in the interface
    
    # Setup the environment based on model selection
    os.environ["OPENAI_MODEL_NAME"] = model_option
    
    # Creating Agents
    # Agent: Data Analyst
    data_analyst_agent = Agent(
        role="Data Analyst",
        goal="Monitor and analyze market data in real-time "
            "to identify trends and predict market movements.",
        backstory="Specializing in financial markets, this agent "
                "uses statistical modeling and machine learning "
                "to provide crucial insights. With a knack for data, "
                "the Data Analyst Agent is the cornerstone for "
                "informing trading decisions.",
        verbose=True,
        allow_delegation=True,
        tools = [scrape_tool, search_tool]
    )
    # Agent: Trading Strategy Developer 
    trading_strategy_agent = Agent(
        role="Trading Strategy Developer",
        goal="Develop and test various trading strategies based "
            "on insights from the Data Analyst Agent.",
        backstory="Equipped with a deep understanding of financial "
                "markets and quantitative analysis, this agent "
                "devises and refines trading strategies. It evaluates "
                "the performance of different approaches to determine "
                "the most profitable and risk-averse options.",
        verbose=True,
        allow_delegation=True,
        tools = [scrape_tool, search_tool]
    )
    # Agent: Trade Advisor
    execution_agent = Agent(
        role="Trade Advisor",
        goal="Suggest optimal trade execution strategies "
            "based on approved trading strategies.",
        backstory="This agent specializes in analyzing the timing, price, "
                "and logistical details of potential trades. By evaluating "
                "these factors, it provides well-founded suggestions for "
                "when and how trades should be executed to maximize "
                "efficiency and adherence to strategy.",
        verbose=True,
        allow_delegation=True,
        tools = [scrape_tool, search_tool]
    )
    # Agent: Risk Advisor
    risk_management_agent = Agent(
        role="Risk Advisor",
        goal="Evaluate and provide insights on the risks "
            "associated with potential trading activities.",
        backstory="Armed with a deep understanding of risk assessment models "
                "and market dynamics, this agent scrutinizes the potential "
                "risks of proposed trades. It offers a detailed analysis of "
                "risk exposure and suggests safeguards to ensure that "
                "trading activities align with the firm鈥檚 risk tolerance.",
        verbose=True,
        allow_delegation=True,
        tools = [scrape_tool, search_tool]
    )

    # Creating Tasks
    # Task for Data Analyst Agent: Analyze Market Data
    data_analysis_task = Task(
        description=(
            "Continuously monitor and analyze market data for "
            "the selected stock ({stock_selection}). "
            "Use statistical modeling and machine learning to "
            "identify trends and predict market movements."
        ),
        expected_output=(
            "Insights and alerts about significant market "
            "opportunities or threats for {stock_selection}."
        ),
        agent=data_analyst_agent,
    )

    # Task for Trading Strategy Agent: Develop Trading Strategies
    strategy_development_task = Task(
        description=(
            "Develop and refine trading strategies based on "
            "the insights from the Data Analyst and "
            "user-defined risk tolerance ({risk_tolerance}). "
            "Consider trading preferences ({trading_strategy_preference})."
        ),
        expected_output=(
            "A set of potential trading strategies for {stock_selection} "
            "that align with the user's risk tolerance."
        ),
        agent=trading_strategy_agent,
    )

    # Task for Trade Advisor Agent: Plan Trade Execution
    execution_planning_task = Task(
        description=(
            "Analyze approved trading strategies to determine the "
            "best execution methods for {stock_selection}, "
            "considering current market conditions and optimal pricing."
        ),
        expected_output=(
            "Detailed execution plans suggesting how and when to "
            "execute trades for {stock_selection}."
        ),
        agent=execution_agent,
    )

    # Task for Risk Advisor Agent: Assess Trading Risks
    risk_assessment_task = Task(
        description=(
            "Evaluate the risks associated with the proposed trading "
            "strategies and execution plans for {stock_selection}. "
            "Provide a detailed analysis of potential risks "
            "and suggest mitigation strategies."
        ),
        expected_output=(
            "A comprehensive risk analysis report detailing potential "
            "risks and mitigation recommendations for {stock_selection}."
            "Provide your final answer in Spanish."
        ),
        agent=risk_management_agent,
    )
    
    # Creating the Crew
    # Note: The Process class helps to delegate the workflow to the Agents (kind of like a Manager at work)
    #       In this example, it will run this hierarchically.
    #       manager_llm lets you choose the "manager" LLM you want to use.

    # Define the crew with agents and tasks
    financial_trading_crew = Crew(
        agents=[data_analyst_agent,
                trading_strategy_agent,
                execution_agent,
                risk_management_agent],

        tasks=[data_analysis_task,
            strategy_development_task,
            execution_planning_task,
            risk_assessment_task],

        manager_llm=ChatOpenAI(model=model_option,
                            temperature=0.7),
        process=Process.hierarchical,
        verbose=True
    )
    
    # Define your inputs
    financial_trading_inputs = {
        'stock_selection': stock_selection,
        'initial_capital': initial_capital,
        'risk_tolerance': risk_tolerance,
        'trading_strategy_preference': trading_strategy_preference,
        'news_impact_consideration': True
    }

    # Execute your Crew process
    result = financial_trading_crew.kickoff(inputs=financial_trading_inputs)
    verbose_output = sys.stdout.getvalue()
    sys.stdout = sys.__stdout__  # Restaurar la salida est谩ndar

    # Convertir el objeto 'result' a cadena para que Gradio pueda procesarlo
    return str(result), verbose_output

#
#execute_financial_analysis( 'VOD', 'gpt-4o-mini', '100000', 'Medium', 'Day Trading' )

#
with gr.Blocks() as demo:
    gr.Markdown("# Colaboraci贸n Multiagente para el An谩lisis Financiero")
    with gr.Sidebar():
        gr.Markdown("# DEMO")
        gr.Image("images/Logo_AB.png")
        gr.Markdown("Contact: [email protected] [email protected]")
        gr.Markdown("## Configuraci贸n del Modelo")
        model_option = gr.Dropdown(MODEL_LIST, label="Choose OpenAI model", value='gpt-4o-mini')

    gr.Markdown("## Configuraci贸n")
    gr.Markdown("""
        ## 馃搳 AI Agents para An谩lisis de Trading
        
        **Este DEMO crea un sistema de agentes de inteligencia artificial (AI Agents) para analizar datos del mercado financiero y sugerir estrategias de trading para un activo.**
        La tripulaci贸n de agentes incluye a:
        * Data Analyst
        * Trading Strategy Developer
        * Trade Advisor
        * Risk Advisor
        
        Todos, con herramientas de acceso a informaci贸n en tiempo real que sea disponible en Internet.
        Por favor, selecciona el **Ticker** respecto del cual quieras el an谩lisis financiero.
        
        Algunos ejemplos son:
        - VOD - Nasdaq Index
        - AAPL - Apple
        - GOOG - Alphabet (Google)
        - INTC - Intel
        - BTC-USD - Bitcoin USD
        """)
    ticker = gr.Textbox(label="Introduce el Ticker del activo financiero (Ej: AAPL):", value="AAPL")
    initial_capital = gr.Textbox(label="Initial Capital", value="100000")
    risk_tolerance = gr.Radio(label="Risk Tolerance", choices=["Low", "Medium", "High"], value="Medium")
    trading_strategy_preference = gr.Radio(label="Trading Strategy Preference", choices=["Day Trading", "Swing Trading", "Long Term"], value="Day Trading")
    execute_button = gr.Button("馃殌 Iniciar An谩lisis")

    gr.Markdown("## 馃搶 Resultado Final")
    result_display = gr.Markdown()
    verbose_output = gr.Textbox(label="馃攷 Detalle del Proceso de Razonamiento", lines=10)

    execute_button.click(
        execute_financial_analysis,
        inputs=[ticker, model_option, initial_capital, risk_tolerance, trading_strategy_preference],
        outputs=[result_display, verbose_output]
    )
#
demo.launch()