Benjov commited on
Commit
66a4fc3
1 Parent(s): adc18c4
Files changed (4) hide show
  1. .DS_Store +0 -0
  2. app.py +259 -0
  3. images/Logo_AB.png +0 -0
  4. requirements.txt +7 -0
.DS_Store ADDED
Binary file (6.15 kB). View file
 
app.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ANAL脥TICA BOUTIQUE, SC (https://www.visoresanalitica.com.mx/)
2
+ # DEMO
3
+ #
4
+ # PROBLEM:
5
+
6
+ # Multi-agent Collaboration for Financial Analysis
7
+ # Demostrate ways for making agents collaborate with each other.
8
+ #
9
+
10
+ # python app.py
11
+
12
+ # Dependencies:
13
+ import gradio as gr
14
+ from crewai import Agent, Task, Crew, Process
15
+ from langchain_openai import ChatOpenAI
16
+ #from langchain_community.chat_message_histories import GradioChatMessageHistory
17
+ from langchain_community.chat_message_histories.in_memory import ChatMessageHistory
18
+ import os
19
+ import sys
20
+ import io
21
+ import pandas as pd
22
+ from crewai_tools import SerperDevTool, ScrapeWebsiteTool
23
+ #from scrape_website_tool import ScrapeWebsiteTool
24
+ #from serper_dev_tool import SerperDevTool
25
+
26
+ #
27
+ # Obtener las API keys desde .env
28
+ openai_api_key = os.getenv("OPENAI_API_KEY")
29
+ serper_api_key = os.getenv("SERPER_API_KEY")
30
+
31
+ # Obtener las API keys desde SECRETS
32
+ #openai_api_key = st.secrets["OPENAI_API_KEY"]
33
+ #serper_api_key = st.secrets["SERPER_API_KEY"]
34
+
35
+ # Define the list of models and initialize your agents and tasks as per the earlier code
36
+ MODEL_LIST = ['gpt-4o-mini', 'gpt-4o']
37
+
38
+ # crewAI Tools
39
+ search_tool = SerperDevTool()
40
+ scrape_tool = ScrapeWebsiteTool()
41
+
42
+ # Define Gradio interface components
43
+ def execute_financial_analysis( stock_selection, model_option, initial_capital, risk_tolerance, trading_strategy_preference ):
44
+ sys.stdout = io.StringIO() # Capture output to display in the interface
45
+
46
+ # Setup the environment based on model selection
47
+ os.environ["OPENAI_MODEL_NAME"] = model_option
48
+
49
+ # Creating Agents
50
+ # Agent: Data Analyst
51
+ data_analyst_agent = Agent(
52
+ role="Data Analyst",
53
+ goal="Monitor and analyze market data in real-time "
54
+ "to identify trends and predict market movements.",
55
+ backstory="Specializing in financial markets, this agent "
56
+ "uses statistical modeling and machine learning "
57
+ "to provide crucial insights. With a knack for data, "
58
+ "the Data Analyst Agent is the cornerstone for "
59
+ "informing trading decisions.",
60
+ verbose=True,
61
+ allow_delegation=True,
62
+ tools = [scrape_tool, search_tool]
63
+ )
64
+ # Agent: Trading Strategy Developer
65
+ trading_strategy_agent = Agent(
66
+ role="Trading Strategy Developer",
67
+ goal="Develop and test various trading strategies based "
68
+ "on insights from the Data Analyst Agent.",
69
+ backstory="Equipped with a deep understanding of financial "
70
+ "markets and quantitative analysis, this agent "
71
+ "devises and refines trading strategies. It evaluates "
72
+ "the performance of different approaches to determine "
73
+ "the most profitable and risk-averse options.",
74
+ verbose=True,
75
+ allow_delegation=True,
76
+ tools = [scrape_tool, search_tool]
77
+ )
78
+ # Agent: Trade Advisor
79
+ execution_agent = Agent(
80
+ role="Trade Advisor",
81
+ goal="Suggest optimal trade execution strategies "
82
+ "based on approved trading strategies.",
83
+ backstory="This agent specializes in analyzing the timing, price, "
84
+ "and logistical details of potential trades. By evaluating "
85
+ "these factors, it provides well-founded suggestions for "
86
+ "when and how trades should be executed to maximize "
87
+ "efficiency and adherence to strategy.",
88
+ verbose=True,
89
+ allow_delegation=True,
90
+ tools = [scrape_tool, search_tool]
91
+ )
92
+ # Agent: Risk Advisor
93
+ risk_management_agent = Agent(
94
+ role="Risk Advisor",
95
+ goal="Evaluate and provide insights on the risks "
96
+ "associated with potential trading activities.",
97
+ backstory="Armed with a deep understanding of risk assessment models "
98
+ "and market dynamics, this agent scrutinizes the potential "
99
+ "risks of proposed trades. It offers a detailed analysis of "
100
+ "risk exposure and suggests safeguards to ensure that "
101
+ "trading activities align with the firm鈥檚 risk tolerance.",
102
+ verbose=True,
103
+ allow_delegation=True,
104
+ tools = [scrape_tool, search_tool]
105
+ )
106
+
107
+ # Creating Tasks
108
+ # Task for Data Analyst Agent: Analyze Market Data
109
+ data_analysis_task = Task(
110
+ description=(
111
+ "Continuously monitor and analyze market data for "
112
+ "the selected stock ({stock_selection}). "
113
+ "Use statistical modeling and machine learning to "
114
+ "identify trends and predict market movements."
115
+ ),
116
+ expected_output=(
117
+ "Insights and alerts about significant market "
118
+ "opportunities or threats for {stock_selection}."
119
+ ),
120
+ agent=data_analyst_agent,
121
+ )
122
+
123
+ # Task for Trading Strategy Agent: Develop Trading Strategies
124
+ strategy_development_task = Task(
125
+ description=(
126
+ "Develop and refine trading strategies based on "
127
+ "the insights from the Data Analyst and "
128
+ "user-defined risk tolerance ({risk_tolerance}). "
129
+ "Consider trading preferences ({trading_strategy_preference})."
130
+ ),
131
+ expected_output=(
132
+ "A set of potential trading strategies for {stock_selection} "
133
+ "that align with the user's risk tolerance."
134
+ ),
135
+ agent=trading_strategy_agent,
136
+ )
137
+
138
+ # Task for Trade Advisor Agent: Plan Trade Execution
139
+ execution_planning_task = Task(
140
+ description=(
141
+ "Analyze approved trading strategies to determine the "
142
+ "best execution methods for {stock_selection}, "
143
+ "considering current market conditions and optimal pricing."
144
+ ),
145
+ expected_output=(
146
+ "Detailed execution plans suggesting how and when to "
147
+ "execute trades for {stock_selection}."
148
+ ),
149
+ agent=execution_agent,
150
+ )
151
+
152
+ # Task for Risk Advisor Agent: Assess Trading Risks
153
+ risk_assessment_task = Task(
154
+ description=(
155
+ "Evaluate the risks associated with the proposed trading "
156
+ "strategies and execution plans for {stock_selection}. "
157
+ "Provide a detailed analysis of potential risks "
158
+ "and suggest mitigation strategies."
159
+ ),
160
+ expected_output=(
161
+ "A comprehensive risk analysis report detailing potential "
162
+ "risks and mitigation recommendations for {stock_selection}."
163
+ "Provide your final answer in Spanish."
164
+ ),
165
+ agent=risk_management_agent,
166
+ )
167
+
168
+ # Creating the Crew
169
+ # Note: The Process class helps to delegate the workflow to the Agents (kind of like a Manager at work)
170
+ # In this example, it will run this hierarchically.
171
+ # manager_llm lets you choose the "manager" LLM you want to use.
172
+
173
+ # Define the crew with agents and tasks
174
+ financial_trading_crew = Crew(
175
+ agents=[data_analyst_agent,
176
+ trading_strategy_agent,
177
+ execution_agent,
178
+ risk_management_agent],
179
+
180
+ tasks=[data_analysis_task,
181
+ strategy_development_task,
182
+ execution_planning_task,
183
+ risk_assessment_task],
184
+
185
+ manager_llm=ChatOpenAI(model=model_option,
186
+ temperature=0.7),
187
+ process=Process.hierarchical,
188
+ verbose=True
189
+ )
190
+
191
+ # Define your inputs
192
+ financial_trading_inputs = {
193
+ 'stock_selection': stock_selection,
194
+ 'initial_capital': initial_capital,
195
+ 'risk_tolerance': risk_tolerance,
196
+ 'trading_strategy_preference': trading_strategy_preference,
197
+ 'news_impact_consideration': True
198
+ }
199
+
200
+ # Execute your Crew process
201
+ result = financial_trading_crew.kickoff(inputs=financial_trading_inputs)
202
+ verbose_output = sys.stdout.getvalue()
203
+ sys.stdout = sys.__stdout__ # Restaurar la salida est谩ndar
204
+
205
+ # Convertir el objeto 'result' a cadena para que Gradio pueda procesarlo
206
+ return str(result), verbose_output
207
+
208
+ #
209
+ #execute_financial_analysis( 'VOD', 'gpt-4o-mini', '100000', 'Medium', 'Day Trading' )
210
+
211
+ #
212
+ with gr.Blocks() as demo:
213
+ gr.Markdown("# Colaboraci贸n Multiagente para el An谩lisis Financiero")
214
+ with gr.Sidebar():
215
+ gr.Markdown("# DEMO")
216
+ gr.Image("images/Logo_AB.png")
217
218
+ gr.Markdown("## Configuraci贸n del Modelo")
219
+ model_option = gr.Dropdown(MODEL_LIST, label="Choose OpenAI model", value='gpt-4o-mini')
220
+
221
+ gr.Markdown("## Configuraci贸n")
222
+ gr.Markdown("""
223
+ ## 馃搳 AI Agents para An谩lisis de Trading
224
+
225
+ **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.**
226
+ La tripulaci贸n de agentes incluye a:
227
+ * Data Analyst
228
+ * Trading Strategy Developer
229
+ * Trade Advisor
230
+ * Risk Advisor
231
+
232
+ Todos, con herramientas de acceso a informaci贸n en tiempo real que sea disponible en Internet.
233
+ Por favor, selecciona el **Ticker** respecto del cual quieras el an谩lisis financiero.
234
+
235
+ Algunos ejemplos son:
236
+ - VOD - Nasdaq Index
237
+ - AAPL - Apple
238
+ - GOOG - Alphabet (Google)
239
+ - INTC - Intel
240
+ - BTC-USD - Bitcoin USD
241
+ """)
242
+ ticker = gr.Textbox(label="Introduce el Ticker del activo financiero (Ej: AAPL):", value="AAPL")
243
+ initial_capital = gr.Textbox(label="Initial Capital", value="100000")
244
+ risk_tolerance = gr.Radio(label="Risk Tolerance", choices=["Low", "Medium", "High"], value="Medium")
245
+ trading_strategy_preference = gr.Radio(label="Trading Strategy Preference", choices=["Day Trading", "Swing Trading", "Long Term"], value="Day Trading")
246
+ execute_button = gr.Button("馃殌 Iniciar An谩lisis")
247
+
248
+ gr.Markdown("## 馃搶 Resultado Final")
249
+ result_display = gr.Markdown()
250
+ verbose_output = gr.Textbox(label="馃攷 Detalle del Proceso de Razonamiento", lines=10)
251
+
252
+ execute_button.click(
253
+ execute_financial_analysis,
254
+ inputs=[ticker, model_option, initial_capital, risk_tolerance, trading_strategy_preference],
255
+ outputs=[result_display, verbose_output]
256
+ )
257
+ #
258
+ demo.launch()
259
+
images/Logo_AB.png ADDED
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ pandas
2
+ gradio
3
+ crewai
4
+ crewai_tools
5
+ langchain_openai
6
+ langchain_community
7
+