Spaces:
Runtime error
Runtime error
File size: 13,510 Bytes
c83939c 06706c8 c83939c 258d538 c83939c 70d8a6a 27ea219 70d8a6a 27ea219 70d8a6a 4e0d004 70d8a6a c83939c 059f22e 6fb6382 059f22e c83939c 70d8a6a e2bbc85 059f22e c83939c 8e887a9 c83939c 1e22b3f c83939c 7aff307 f0888c9 7aff307 c83939c |
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 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 |
import warnings
warnings.filterwarnings('ignore')
from crewai import Agent, Task, Crew
from crewai import Crew, Process
from langchain_openai import ChatOpenAI
from crewai_tools import ScrapeWebsiteTool, SerperDevTool
import gradio as gr
import os
os.environ["SERPER_API_KEY"] = os.getenv('SERPER_API_KEY')
search_tool = SerperDevTool()
scrape_tool = ScrapeWebsiteTool()
# llm=ChatOpenAI(model="gpt-4o-mini", openai_api_key =os.getenv('OPENAI_API_KEY'), temperature=0.7)
from langchain_community.llms import HuggingFaceEndpoint
llm = HuggingFaceEndpoint(
repo_id="tiiuae/falcon-7b-instruct",
huggingfacehub_api_token=os.getenv('HF_KEY'),
task="text-generation",
temperature=0.7,
)
manager = Agent(
role="Project Manager",
goal="Efficiently manage the crew and ensure high-quality task completion",
backstory="You're an experienced project manager, specialized in financial investments & trading, skilled in overseeing complex projects and guiding teams to success. Your role is to coordinate the efforts of the crew members, ensuring that each task is completed on time and to the highest standard.",
allow_delegation=True,
tools = [scrape_tool, search_tool],
llm=llm
)
data_analyst_agent = Agent(
role="Data Analyst",
goal="First step is to monitor markets in the given country to identify companies with "
"highest investments or contribution to "
"socially responsible causes like CSR (corporate social responsibility), "
"ESG (environment, social and governance), chaity trust etc.,. "
"Main goal is to monitor and analyze market data of only these stock trading codes "
"identified in first step in real-time to identify trends and predict market movements.",
backstory="Specializing in social responsible activities and 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],
llm=llm
)
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, portfolio analysis and quantitative analysis, "
"this agent devises and refines trading strategies. "
"Given a set of stock code options (for example a set of 5 codes) along with "
"the number of top stocks to be shortlisted from the same set of stock code options (for example 3 out of the given 5) "
"and the total initial capital to be invested in the shortlisted stocks "
"in order to decide on portfolio of stocks to invest-in. "
"It evaluates the performance of different approaches to determine "
"the most profitable and risk-averse options "
"before recommending the portfolio of stocks, their quantities and investment amount allocation.",
verbose=True,
allow_delegation=True,
tools = [scrape_tool, search_tool],
llm=llm
)
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],
llm=llm
)
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’s risk tolerance.",
verbose=True,
allow_delegation=True,
tools = [scrape_tool, search_tool],
llm=llm
)
# Task for Data Analyst Agent: Analyze Market Data
data_analysis_task = Task(
description=(
"Must consider the country of interest ({country}). "
"Continuously monitor and analyze market data for "
"5 or more companies in the given country ({country}) with highest investments or contribution to "
"socially responsible causes like CSR (corporate social responsibility), "
"ESG (environment, social and governance), chaity trust etc.,. "
"Obtain stock trading codes for at least 5 companies and "
"assign them as the potential optional stocks list for investment "
"to an input variable >>> 'stock_set', which will be used for further processing and "
"generating the variable >>> 'stock_selecton'. "
"Use market research, statistical modeling and machine learning to "
"identify trends and predict market movements."
),
expected_output=(
"The identified list of company trading codes with highest investments "
"in CSR activities >>> ({stock_set}) in the country of interest ({country}) "
"with rationale why they were selected must appear in the report. "
"Insights and alerts about significant market "
"opportunities or threats for each of the stocks in {stock_set}."
),
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}). "
"Must consider the country of interest ({country}) and total initial capital ({initial_capital}), "
"trading preferences ({trading_strategy_preference}), "
"and how many stock options to be selected ({n_stock_options}) "
"from the given potential optional stocks list for investment ({stock_set}) identified by data_analyst_agent "
"and arrive at a short list of selected stocks for investment."
"Assign this shortlist as values to the input variable >>> 'stock_selection' for further processing."
),
expected_output=(
"The shortlist of selected stocks for investment >>> ({stock_selection}) must appear in the output. "
"A brief on why the stocks in ({stock_selection}) were selected and why not others "
"must appear in the output "
"A set of potential trading strategies for ({stock_selection}) that align with the user's risk tolerance."
"An estimation of quantities and investment amount for each of the selected stocks in ({stock_selection}) "
"to appear in the output. "
"Under each trading strategy, briefly explain why certain stocks from ({stock_selection}) are cosidered "
"and why not others. This to appear in the output. "
),
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} that was recommended by trading_strategy_agent, "
"considering current market conditions and optimal pricing."
),
expected_output=(
"Detailed execution plans suggesting how and when to "
"execute trades for {stock_selection} that was recommended by trading_strategy_agent."
),
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} that was recommended by trading_strategy_agent. "
"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} that was recommended by trading_strategy_agent."
),
agent=risk_management_agent,
)
# 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="gpt-4o-mini", openai_api_key =os.getenv('OPENAI_API_KEY'), temperature=0.7),
# manager_llm=ChatOpenAI(model="mistralai/Mistral-7B-Instruct-v0.3", temperature=0.7),
manager_agent=manager,
full_output =True,
# process=Process.hierarchical,
verbose=True
)
# Function to handle the inputs and display the results
def process_input(country, n_stocks, capital, risk_label, strategy_label, news_impact):
financial_trading_inputs = {
'country' : country.strip().capitalize(),
'stock_set': [],
'stock_selection': [],
'n_stock_options': int(n_stocks),
'initial_capital': int(capital),
'risk_tolerance': risk_label.strip(),
'trading_strategy_preference': strategy_label.strip(),
'news_impact_consideration': news_impact
}
result = financial_trading_crew.kickoff(inputs=financial_trading_inputs)
# global result
output1 = result['tasks_outputs'][0].exported_output+'\n\n=================================\n=================================\n'
output2 = result['tasks_outputs'][1].exported_output
output3 = result['tasks_outputs'][2].exported_output+'\n\n=================================\n=================================\n'
output4 = result['tasks_outputs'][3].exported_output
return output1, output2, output3, output4
# Create the input fields
country = gr.Textbox(label="Country Name", placeholder="Enter country name", value="USA")
n_stocks = gr.Slider(label="How Many Different Stocks You Want to Invest-in?", minimum=1, maximum=10, step=1, value=5)
initial_capital = gr.Number(label="How much capital you would like to invest", minimum=50000, maximum=100000000, step=10000,value=500000)
risk_label = gr.Dropdown(label="Your Risk Appetite Level", choices=["high", "medium", "low"], value="medium")
trading_strategy = gr.Dropdown(
label="Select Trading Strategy",
choices=["day time trading", "swing trading", "scalping", "position trading", "algorithmic trading", "arbitrage", "news-based trading"],
value="swing trading"
)
news_impact = gr.Radio(label="News Impact Consideration", choices=[True, False], value=True)
# Create markdown output fields
output1 = gr.Markdown(label="Companies Identified with Significant Investments in Social, Charitable, Environmental Activities")
output2 = gr.Markdown(label="Stocks Identified for Investment")
output3 = gr.Markdown(label="Investment Execution Startegies")
output4 = gr.Markdown(label="Risks & Mitigation strategies")
# Create submit and clear buttons
submit_button = gr.Button("Submit")
clear_button = gr.Button("Clear")
# Create the layout and interface
with gr.Blocks() as app:
gr.Markdown("""# A Platform for Investing in Socially Responsible Companies in Your Country of Choice
### After entering the details and hitting Submit button, wait for about 15 to 30 mts minutes for the results to appear. After all, the agents are doing lots of reserach work on all internet data. Get a coffee, sit back and relax😀😀. You will be pleasantly surprised with the results😀😀""")
with gr.Row():
with gr.Column():
country.render()
n_stocks.render()
initial_capital.render()
with gr.Column():
risk_label.render()
trading_strategy.render()
news_impact.render()
with gr.Row():
with gr.Column():
output1.render()
output2.render()
with gr.Column():
output3.render()
output4.render()
with gr.Row(): # Add the submit and clear buttons
submit_button.render()
clear_button.render()
# Link inputs and outputs to the submit button
submit_button.click(
fn=process_input,
inputs=[country, n_stocks, initial_capital, risk_label, trading_strategy, news_impact],
outputs=[output1, output2, output3, output4]
)
# Link the clear button to reset inputs and outputs
clear_button.click(
fn=lambda: ("", "", "", ""), # Clear all outputs
inputs=[],
outputs=[output1, output2, output3, output4]
)
# Link inputs and outputs to function
submit_button.click(
fn=process_input,
inputs=[country, n_stocks, initial_capital, risk_label, trading_strategy, news_impact],
outputs=[output1, output2, output3, output4]
)
# Launch the app
app.launch(debug=True) |