vsrinivas's picture
Update app.py
7aff307 verified
raw
history blame
12.5 kB
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)
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),
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="Select True or False", 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 hit Submit button, wait for few minutes for the results to appear. 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)