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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import warnings
|
2 |
+
warnings.filterwarnings('ignore')
|
3 |
+
|
4 |
+
from crewai import Agent, Task, Crew
|
5 |
+
from crewai import Crew, Process
|
6 |
+
from langchain_openai import ChatOpen
|
7 |
+
from crewai_tools import ScrapeWebsiteTool, SerperDevTool
|
8 |
+
import gradio as gr
|
9 |
+
import os
|
10 |
+
|
11 |
+
os.environ["SERPER_API_KEY"] = os.envget('SERPER_API_KEY
|
12 |
+
|
13 |
+
search_tool = SerperDevTool()
|
14 |
+
scrape_tool = ScrapeWebsiteTool()
|
15 |
+
llm=ChatOpenAI(model="gpt-4o-mini", openai_api_key =os.envget('OPENAI_API_KEY'), temperature=0.7)
|
16 |
+
|
17 |
+
data_analyst_agent = Agent(
|
18 |
+
role="Data Analyst",
|
19 |
+
goal="First step is to monitor markets in the given country to identify companies with "
|
20 |
+
"highest investments or contribution to "
|
21 |
+
"socially responsible causes like CSR (corporate social responsibility), "
|
22 |
+
"ESG (environment, social and governance), chaity trust etc.,. "
|
23 |
+
"Main goal is to monitor and analyze market data of only these stock trading codes "
|
24 |
+
"identified in first step in real-time to identify trends and predict market movements.",
|
25 |
+
backstory="Specializing in social responsible activities and financial markets, this agent "
|
26 |
+
"uses statistical modeling and machine learning "
|
27 |
+
"to provide crucial insights. With a knack for data, "
|
28 |
+
"the Data Analyst Agent is the cornerstone for "
|
29 |
+
"informing trading decisions.",
|
30 |
+
verbose=True,
|
31 |
+
allow_delegation=True,
|
32 |
+
tools = [scrape_tool, search_tool],
|
33 |
+
llm=llm
|
34 |
+
)
|
35 |
+
|
36 |
+
trading_strategy_agent = Agent(
|
37 |
+
role="Trading Strategy Developer",
|
38 |
+
goal="Develop and test various trading strategies based "
|
39 |
+
"on insights from the Data Analyst Agent.",
|
40 |
+
backstory="Equipped with a deep understanding of financial "
|
41 |
+
"markets, portfolio analysis and quantitative analysis, "
|
42 |
+
"this agent devises and refines trading strategies. "
|
43 |
+
"Given a set of stock code options (for example a set of 5 codes) along with "
|
44 |
+
"the number of top stocks to be shortlisted from the same set of stock code options (for example 3 out of the given 5) "
|
45 |
+
"and the total initial capital to be invested in the shortlisted stocks "
|
46 |
+
"in order to decide on portfolio of stocks to invest-in. "
|
47 |
+
"It evaluates the performance of different approaches to determine "
|
48 |
+
"the most profitable and risk-averse options "
|
49 |
+
"before recommending the portfolio of stocks, their quantities and investment amount allocation.",
|
50 |
+
verbose=True,
|
51 |
+
allow_delegation=True,
|
52 |
+
tools = [scrape_tool, search_tool],
|
53 |
+
llm=llm
|
54 |
+
)
|
55 |
+
|
56 |
+
execution_agent = Agent(
|
57 |
+
role="Trade Advisor",
|
58 |
+
goal="Suggest optimal trade execution strategies "
|
59 |
+
"based on approved trading strategies.",
|
60 |
+
backstory="This agent specializes in analyzing the timing, price, "
|
61 |
+
"and logistical details of potential trades. By evaluating "
|
62 |
+
"these factors, it provides well-founded suggestions for "
|
63 |
+
"when and how trades should be executed to maximize "
|
64 |
+
"efficiency and adherence to strategy.",
|
65 |
+
verbose=True,
|
66 |
+
allow_delegation=True,
|
67 |
+
tools = [scrape_tool, search_tool],
|
68 |
+
llm=llm
|
69 |
+
)
|
70 |
+
|
71 |
+
risk_management_agent = Agent(
|
72 |
+
role="Risk Advisor",
|
73 |
+
goal="Evaluate and provide insights on the risks "
|
74 |
+
"associated with potential trading activities.",
|
75 |
+
backstory="Armed with a deep understanding of risk assessment models "
|
76 |
+
"and market dynamics, this agent scrutinizes the potential "
|
77 |
+
"risks of proposed trades. It offers a detailed analysis of "
|
78 |
+
"risk exposure and suggests safeguards to ensure that "
|
79 |
+
"trading activities align with the firm’s risk tolerance.",
|
80 |
+
verbose=True,
|
81 |
+
allow_delegation=True,
|
82 |
+
tools = [scrape_tool, search_tool],
|
83 |
+
llm=llm
|
84 |
+
)
|
85 |
+
|
86 |
+
# Task for Data Analyst Agent: Analyze Market Data
|
87 |
+
data_analysis_task = Task(
|
88 |
+
description=(
|
89 |
+
"Must consider the country of interest ({country}). "
|
90 |
+
"Continuously monitor and analyze market data for "
|
91 |
+
"5 or more companies in the given country ({country}) with highest investments or contribution to "
|
92 |
+
"socially responsible causes like CSR (corporate social responsibility), "
|
93 |
+
"ESG (environment, social and governance), chaity trust etc.,. "
|
94 |
+
"Obtain stock trading codes for at least 5 companies and "
|
95 |
+
"assign them as the potential optional stocks list for investment "
|
96 |
+
"to an input variable >>> 'stock_set', which will be used for further processing and "
|
97 |
+
"generating the variable >>> 'stock_selecton'. "
|
98 |
+
"Use market research, statistical modeling and machine learning to "
|
99 |
+
"identify trends and predict market movements."
|
100 |
+
),
|
101 |
+
expected_output=(
|
102 |
+
"The identified list of company trading codes with highest investments "
|
103 |
+
"in CSR activities >>> ({stock_set}) in the country of interest ({country}) "
|
104 |
+
"with rationale why they were selected must appear in the report. "
|
105 |
+
"Insights and alerts about significant market "
|
106 |
+
"opportunities or threats for each of the stocks in {stock_set}."
|
107 |
+
),
|
108 |
+
agent=data_analyst_agent,
|
109 |
+
)
|
110 |
+
|
111 |
+
# Task for Trading Strategy Agent: Develop Trading Strategies
|
112 |
+
strategy_development_task = Task(
|
113 |
+
description=(
|
114 |
+
"Develop and refine trading strategies based on "
|
115 |
+
"the insights from the Data Analyst and "
|
116 |
+
"user-defined risk tolerance ({risk_tolerance}). "
|
117 |
+
"Must consider the country of interest ({country}) and total initial capital ({initial_capital}), "
|
118 |
+
"trading preferences ({trading_strategy_preference}), "
|
119 |
+
"and how many stock options to be selected ({n_stock_options}) "
|
120 |
+
"from the given potential optional stocks list for investment ({stock_set}) identified by data_analyst_agent "
|
121 |
+
"and arrive at a short list of selected stocks for investment."
|
122 |
+
"Assign this shortlist as values to the input variable >>> 'stock_selection' for further processing."
|
123 |
+
),
|
124 |
+
expected_output=(
|
125 |
+
"The shortlist of selected stocks for investment >>> ({stock_selection}) must appear in the output. "
|
126 |
+
"A brief on why the stocks in ({stock_selection}) were selected and why not others "
|
127 |
+
"must appear in the output "
|
128 |
+
"A set of potential trading strategies for ({stock_selection}) that align with the user's risk tolerance."
|
129 |
+
"An estimation of quantities and investment amount for each of the selected stocks in ({stock_selection}) "
|
130 |
+
"to appear in the output. "
|
131 |
+
"Under each trading strategy, briefly explain why certain stocks from ({stock_selection}) are cosidered "
|
132 |
+
"and why not others. This to appear in the output. "
|
133 |
+
),
|
134 |
+
agent=trading_strategy_agent,
|
135 |
+
)
|
136 |
+
|
137 |
+
# Task for Trade Advisor Agent: Plan Trade Execution
|
138 |
+
execution_planning_task = Task(
|
139 |
+
description=(
|
140 |
+
"Analyze approved trading strategies to determine the "
|
141 |
+
"best execution methods for {stock_selection} that was recommended by trading_strategy_agent, "
|
142 |
+
"considering current market conditions and optimal pricing."
|
143 |
+
),
|
144 |
+
expected_output=(
|
145 |
+
"Detailed execution plans suggesting how and when to "
|
146 |
+
"execute trades for {stock_selection} that was recommended by trading_strategy_agent."
|
147 |
+
),
|
148 |
+
agent=execution_agent,
|
149 |
+
)
|
150 |
+
|
151 |
+
# Task for Risk Advisor Agent: Assess Trading Risks
|
152 |
+
risk_assessment_task = Task(
|
153 |
+
description=(
|
154 |
+
"Evaluate the risks associated with the proposed trading "
|
155 |
+
"strategies and execution plans for {stock_selection} that was recommended by trading_strategy_agent. "
|
156 |
+
"Provide a detailed analysis of potential risks "
|
157 |
+
"and suggest mitigation strategies."
|
158 |
+
),
|
159 |
+
expected_output=(
|
160 |
+
"A comprehensive risk analysis report detailing potential "
|
161 |
+
"risks and mitigation recommendations for {stock_selection} that was recommended by trading_strategy_agent."
|
162 |
+
),
|
163 |
+
agent=risk_management_agent,
|
164 |
+
)
|
165 |
+
|
166 |
+
# Define the crew with agents and tasks
|
167 |
+
financial_trading_crew = Crew(
|
168 |
+
agents=[data_analyst_agent,
|
169 |
+
trading_strategy_agent,
|
170 |
+
execution_agent,
|
171 |
+
risk_management_agent],
|
172 |
+
|
173 |
+
tasks=[data_analysis_task,
|
174 |
+
strategy_development_task,
|
175 |
+
execution_planning_task,
|
176 |
+
risk_assessment_task],
|
177 |
+
|
178 |
+
manager_llm=ChatOpenAI(model="gpt-4o-mini", openai_api_key =os.envget('OPENAI_API_KEY'), temperature=0.7),
|
179 |
+
full_output =True,
|
180 |
+
process=Process.hierarchical,
|
181 |
+
verbose=True
|
182 |
+
)
|
183 |
+
|
184 |
+
# Function to handle the inputs and display the results
|
185 |
+
def process_input(country, n_stocks, capital, risk_label, strategy_label, news_impact):
|
186 |
+
financial_trading_inputs = {
|
187 |
+
'country' : country.strip().capitalize(),
|
188 |
+
'stock_set': [],
|
189 |
+
'stock_selection': [],
|
190 |
+
'n_stock_options': int(n_stocks),
|
191 |
+
'initial_capital': int(capital),
|
192 |
+
'risk_tolerance': risk_label.strip(),
|
193 |
+
'trading_strategy_preference': strategy_label.strip(),
|
194 |
+
'news_impact_consideration': news_impact
|
195 |
+
}
|
196 |
+
|
197 |
+
result = financial_trading_crew.kickoff(inputs=financial_trading_inputs)
|
198 |
+
# global result
|
199 |
+
output1 = result['tasks_outputs'][0].exported_output+'\n\n=================================\n=================================\n'
|
200 |
+
output2 = result['tasks_outputs'][1].exported_output
|
201 |
+
output3 = result['tasks_outputs'][2].exported_output+'\n\n=================================\n=================================\n'
|
202 |
+
output4 = result['tasks_outputs'][3].exported_output
|
203 |
+
return output1, output2, output3, output4
|
204 |
+
|
205 |
+
# Create the input fields
|
206 |
+
country = gr.Textbox(label="Country Name", placeholder="Enter country name", value="USA")
|
207 |
+
n_stocks = gr.Slider(label="How Many Different Stocks You Want to Invest-in?", minimum=1, maximum=10, step=1, value=5)
|
208 |
+
initial_capital = gr.Number(label="How much capital you would like to invest", minimum=50000, maximum=100000000, step=10000,value=500000)
|
209 |
+
risk_label = gr.Dropdown(label="Your Risk Appetite Level", choices=["high", "medium", "low"], value="medium")
|
210 |
+
trading_strategy = gr.Dropdown(
|
211 |
+
label="Select Trading Strategy",
|
212 |
+
choices=["day time trading", "swing trading", "scalping", "position trading", "algorithmic trading", "arbitrage", "news-based trading"],
|
213 |
+
value="swing trading"
|
214 |
+
)
|
215 |
+
news_impact = gr.Radio(label="Select True or False", choices=[True, False], value=True)
|
216 |
+
|
217 |
+
# Create markdown output fields
|
218 |
+
output1 = gr.Markdown(label="Companies Identified with Significant Investments in Social, Charitable, Environmental Activities")
|
219 |
+
output2 = gr.Markdown(label="Stocks Identified for Investment")
|
220 |
+
output3 = gr.Markdown(label="Investment Execution Startegies")
|
221 |
+
output4 = gr.Markdown(label="Risks & Mitigation strategies")
|
222 |
+
|
223 |
+
# Create submit and clear buttons
|
224 |
+
submit_button = gr.Button("Submit")
|
225 |
+
clear_button = gr.Button("Clear")
|
226 |
+
|
227 |
+
# Create the layout and interface
|
228 |
+
with gr.Blocks() as app:
|
229 |
+
with gr.Row():
|
230 |
+
with gr.Column():
|
231 |
+
country.render()
|
232 |
+
n_stocks.render()
|
233 |
+
initial_capital.render()
|
234 |
+
with gr.Column():
|
235 |
+
risk_label.render()
|
236 |
+
trading_strategy.render()
|
237 |
+
news_impact.render()
|
238 |
+
|
239 |
+
with gr.Row():
|
240 |
+
with gr.Column():
|
241 |
+
output1.render()
|
242 |
+
output2.render()
|
243 |
+
with gr.Column():
|
244 |
+
output3.render()
|
245 |
+
output4.render()
|
246 |
+
|
247 |
+
with gr.Row(): # Add the submit and clear buttons
|
248 |
+
submit_button.render()
|
249 |
+
clear_button.render()
|
250 |
+
|
251 |
+
# Link inputs and outputs to the submit button
|
252 |
+
submit_button.click(
|
253 |
+
fn=process_input,
|
254 |
+
inputs=[country, n_stocks, initial_capital, risk_label, trading_strategy, news_impact],
|
255 |
+
outputs=[output1, output2, output3, output4]
|
256 |
+
)
|
257 |
+
|
258 |
+
# Link the clear button to reset inputs and outputs
|
259 |
+
clear_button.click(
|
260 |
+
fn=lambda: ("", "", "", ""), # Clear all outputs
|
261 |
+
inputs=[],
|
262 |
+
outputs=[output1, output2, output3, output4]
|
263 |
+
)
|
264 |
+
# Link inputs and outputs to function
|
265 |
+
submit_button.click(
|
266 |
+
fn=process_input,
|
267 |
+
inputs=[country, n_stocks, initial_capital, risk_label, trading_strategy, news_impact],
|
268 |
+
outputs=[output1, output2, output3, output4]
|
269 |
+
)
|
270 |
+
|
271 |
+
# Launch the app
|
272 |
+
app.launch(debug=True)
|